import React, { useState, useEffect } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer,
  Cell
} from 'recharts';
import { Filter, Activity, Download, Info, CheckCircle, HelpCircle, XCircle } from 'lucide-react';
import { Card } from './common/Card';
import { Tooltip } from './common/Tooltip';
import { dashboardApi, reportApi } from '../services/api';
import type { DashboardKPI, FunnelData, AttributionRow } from '../types';

export const DashboardView: React.FC = () => {
  const [kpi, setKpi] = useState<DashboardKPI>({
    total_dit: 0,
    sample_rate: 0,
    hit_rate: 0,
    fulfillment_rate: 0,
    no_order_sample_rate: 0,
    total_revenue: 0,
  });
  const [funnelData, setFunnelData] = useState<FunnelData[]>([]);
  const [attribution, setAttribution] = useState<AttributionRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<'all' | 'sample' | 'order'>('all');
  const [isExporting, setIsExporting] = useState(false);

  useEffect(() => {
    loadDashboardData();
  }, []);

  const loadDashboardData = async () => {
    try {
      const [kpiData, funnelRes, attrRes] = await Promise.all([
        dashboardApi.getKPI(),
        dashboardApi.getFunnel(),
        dashboardApi.getAttribution(),
      ]);
      setKpi(kpiData);
      setFunnelData(funnelRes);
      setAttribution(attrRes);
    } catch (error) {
      console.error('Error loading dashboard:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async (format: 'xlsx' | 'pdf') => {
    if (isExporting) return;
    setIsExporting(true);
    console.log(`Starting export for ${format}`);
    // alert(`Starting export for ${format}...`); // Debugging
    try {
      const response = format === 'xlsx'
        ? await reportApi.exportExcel()
        : await reportApi.exportPdf();

      console.log('Response received', response);

      const blob = response; // response is already a blob from api.ts
      if (blob.size === 0) {
        alert('Export failed: Received empty file.');
        return;
      }

      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `report.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      console.log('Download triggered');
    } catch (error) {
      console.error('Export error:', error);
      alert(`匯出失敗: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsExporting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  const filteredAttribution = attribution.filter(row => {
    if (filterType === 'sample') return !!row.sample;
    if (filterType === 'order') return !!row.order;
    return true;
  });

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-500">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">業務轉換率戰情室 (v1.0)</h1>
          <p className="text-slate-500 mt-1">
            數據來源：DIT Report, 樣品紀錄, 訂單明細 | 邏輯：瀑布式比對 + LIFO 歸因
          </p>
        </div>
        <button
          onClick={() => handleExport('xlsx')}
          disabled={isExporting}
          className={`flex items-center gap-2 px-4 py-2 border border-slate-300 rounded-lg text-sm font-medium transition-all ${isExporting
            ? 'bg-slate-100 text-slate-400 cursor-not-allowed'
            : 'text-slate-600 hover:bg-slate-50'
            }`}
        >
          {isExporting ? (
            <div className="w-4 h-4 border-2 border-slate-400 border-t-transparent rounded-full animate-spin"></div>
          ) : (
            <Download size={16} />
          )}
          {isExporting ? '匯出中...' : '匯出報表'}
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <Card className="p-4 border-l-4 border-l-indigo-500">
          <div className="text-xs text-slate-500 mb-1">DIT 總案件數</div>
          <div className="text-2xl font-bold text-slate-800">{kpi.total_dit}</div>
          <div className="text-[10px] text-slate-400 mt-1">Total Pipeline</div>
        </Card>
        <Card className="p-4 border-l-4 border-l-purple-500">
          <div className="text-xs text-slate-500 mb-1 flex items-center gap-1">
            送樣轉換率
            <Tooltip content={`送樣轉換率 = (成功送樣的專案數 / DIT 總專案數) * 100%\n反映有多少比例的 DIT 案件成功進入送樣階段。`}>
              <HelpCircle size={12} className="cursor-help text-slate-400 hover:text-purple-600" />
            </Tooltip>
          </div>
          <div className="text-2xl font-bold text-slate-800">{kpi.sample_rate}%</div>
          <div className="text-[10px] text-purple-600 mt-1">Sample Rate</div>
        </Card>
        <Card className="p-4 border-l-4 border-l-emerald-500">
          <div className="text-xs text-slate-500 mb-1 flex items-center gap-1">
            訂單命中率
            <Tooltip content={`訂單命中率 = (取得訂單的專案數 / DIT 總專案數) * 100%\n反映多少比例的 DIT 案件最終成功取得訂單。`}>
              <HelpCircle size={12} className="cursor-help text-slate-400 hover:text-emerald-600" />
            </Tooltip>
          </div>
          <div className="text-2xl font-bold text-slate-800">{kpi.hit_rate}%</div>
          <div className="text-[10px] text-emerald-600 mt-1">Hit Rate (Binary)</div>
        </Card>
        <Card className="p-4 border-l-4 border-l-amber-500">
          <div className="text-xs text-slate-500 mb-1 flex items-center gap-1">
            EAU 達成率
            <Tooltip content={`EAU 達成率 = (歸因訂單總量 / DIT 預估總用量 EAU) * 100%\n反映實際取得的訂單量佔全體潛在商機 (EAU) 的成交比例。`}>
              <HelpCircle size={12} className="cursor-help text-slate-400 hover:text-amber-600" />
            </Tooltip>
          </div>
          <div className="text-2xl font-bold text-slate-800">{kpi.fulfillment_rate}%</div>
          <div className="text-[10px] text-amber-600 mt-1">Fulfillment (LIFO)</div>
        </Card>
        <Card className="p-4 border-l-4 border-l-rose-500">
          <div className="text-xs text-slate-500 mb-1 flex items-center gap-1">
            無訂單樣品率
            <Tooltip content={`無訂單樣品率 = (有送樣但無訂單的專案數 / 成功送樣專案數) * 100%\n反映已送樣但尚未轉單的 DIT 專案比例。`}>
              <HelpCircle size={12} className="cursor-help text-slate-400 hover:text-rose-600" />
            </Tooltip>
          </div>
          <div className="text-2xl font-bold text-rose-600">{kpi.no_order_sample_rate}%</div>
          <div className="text-[10px] text-rose-400 mt-1">No-Order Sample</div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Funnel Chart */}
        <Card className="lg:col-span-2 p-6">
          <h3 className="font-bold text-slate-700 mb-6 flex items-center gap-2">
            <Filter size={18} />
            DIT 轉換漏斗 (Funnel Analysis)
          </h3>
          <div className="h-64 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                layout="vertical"
                data={funnelData}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                <XAxis type="number" />
                <YAxis dataKey="name" type="category" width={100} />
                <RechartsTooltip cursor={{ fill: '#f1f5f9' }} />
                <Bar
                  dataKey="value"
                  barSize={30}
                  radius={[0, 4, 4, 0]}
                  label={{ position: 'right' }}
                  onClick={(data) => {
                    if (data.name === '成功送樣') setFilterType('sample');
                    else if (data.name === '取得訂單') setFilterType('order');
                    else setFilterType('all');
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  {funnelData.map((entry, index) => (
                    <Cell
                      key={`cell-${index}`}
                      fill={entry.fill}
                      fillOpacity={filterType === 'all' || (filterType === 'sample' && entry.name === '成功送樣') || (filterType === 'order' && entry.name === '取得訂單') ? 1 : 0.3}
                    />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </Card>

        {/* Total Revenue Card */}
        <Card className="p-6 flex flex-col justify-center items-center bg-gradient-to-br from-emerald-500 to-teal-600 text-white">
          <Activity size={48} className="mb-4 opacity-80" />
          <h3 className="text-lg font-medium opacity-90">歸因總營收</h3>
          <div className="text-4xl font-bold my-2">
            ${kpi.total_revenue.toLocaleString()}
          </div>
          <p className="text-xs opacity-70 text-center px-4">
            基於 LIFO 邏輯分配至各 DIT 案件之實際訂單金額總和
          </p>
        </Card>
      </div>

      {/* Attribution Table */}
      <Card className="overflow-hidden">
        <div className="bg-slate-50 px-6 py-4 border-b border-slate-200 flex justify-between items-center">
          <div className="flex items-center gap-4">
            <h3 className="font-bold text-slate-700 flex items-center gap-2">
              <Activity size={18} />
              DIT 歸因明細表 (LIFO 業績分配)
            </h3>
            {filterType !== 'all' && (
              <span className="flex items-center gap-1 px-2 py-0.5 bg-indigo-100 text-indigo-700 text-xs font-bold rounded-full animate-in zoom-in duration-300">
                篩選：{filterType === 'sample' ? '成功送樣' : '取得訂單'}
                <button onClick={() => setFilterType('all')} className="hover:text-indigo-900">
                  <XCircle size={14} />
                </button>
              </span>
            )}
          </div>
          <div className="text-xs text-slate-500">
            <span className="flex items-center gap-1">
              <Info size={12} />
              Hover <HelpCircle size={10} /> to see matching logic
            </span>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left">
            <thead className="bg-white text-slate-500 border-b border-slate-200">
              <tr>
                <th className="px-6 py-3">OP編號 / 日期</th>
                <th className="px-6 py-3">Customer / Stage</th>
                <th className="px-6 py-3">Part No.</th>
                <th className="px-6 py-3 text-right">EAU / 歸因量</th>
                <th className="px-6 py-3 text-center">達成率</th>
                <th className="px-6 py-3 text-center">送樣 / 訂單</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filteredAttribution.map((row, i) => (
                <tr key={i} className="hover:bg-slate-50 group transition-colors">
                  <td className="px-6 py-3">
                    <div className="font-mono text-xs text-slate-700 font-bold">{row.dit.op_id}</div>
                    {row.dit.op_name && (
                      <div className="text-[10px] text-indigo-800 truncate max-w-[150px] my-0.5" title={row.dit.op_name}>
                        {row.dit.op_name}
                      </div>
                    )}
                    <div className="text-[10px] text-slate-400">{row.dit.date}</div>
                  </td>
                  <td className="px-6 py-3">
                    <div className="font-medium text-slate-800">{row.dit.customer}</div>
                    <div className="text-[10px] text-slate-400 font-light">{row.dit.stage}</div>
                  </td>
                  <td className="px-6 py-3 font-mono text-slate-600 text-xs">{row.dit.pn}</td>
                  <td className="px-6 py-3 text-right">
                    <div className="font-mono text-slate-600">{row.dit.eau.toLocaleString()}</div>
                    <div className="font-mono text-emerald-600 font-bold">+{row.attributed_qty.toLocaleString()}</div>
                  </td>
                  <td className="px-6 py-3 text-center">
                    <div className={`text-xs font-bold ${row.fulfillment_rate >= 100 ? 'text-emerald-600' : 'text-slate-500'}`}>
                      {row.fulfillment_rate}%
                    </div>
                    <div className="w-16 h-1 bg-slate-100 rounded-full mt-1 mx-auto overflow-hidden">
                      <div
                        className={`h-full ${row.fulfillment_rate >= 100 ? 'bg-emerald-500' : 'bg-indigo-500'}`}
                        style={{ width: `${Math.min(row.fulfillment_rate, 100)}%` }}
                      ></div>
                    </div>
                  </td>
                  <td className="px-6 py-3 text-center">
                    <div className="flex justify-center gap-2">
                      {row.sample ? (
                        <div
                          className="p-1 bg-purple-50 text-purple-700 rounded border border-purple-100 cursor-help"
                          title={`送樣單號: ${row.sample.order_no} (${row.sample.date})`}
                        >
                          <CheckCircle size={14} />
                        </div>
                      ) : (
                        <div className="p-1 text-slate-200"><CheckCircle size={14} /></div>
                      )}
                      {row.order ? (
                        <div
                          className="p-1 bg-emerald-50 text-emerald-700 rounded border border-emerald-100 cursor-help flex items-center gap-1"
                          title={row.match_source || `訂單單號: ${row.order.order_no}`}
                        >
                          <CheckCircle size={14} />
                          <HelpCircle size={10} className="text-emerald-400" />
                        </div>
                      ) : (
                        <div className="p-1 text-slate-200"><CheckCircle size={14} /></div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
};
