import React, { useState, useRef } from 'react';
import {
  FileText, Database, CheckCircle, RefreshCw, Activity,
} from 'lucide-react';
import { Card, Badge } from './common/Card';
import { etlApi, matchApi } from '../services/api';
import type { ParsedFile, DitRecord, OrderRecord } from '../types';

interface ImportViewProps {
  onEtlComplete: () => void;
}

type FileType = 'dit' | 'sample' | 'order';

interface FileState {
  file: File | null;
  parsed: ParsedFile | null;
  loading: boolean;
}

export const ImportView: React.FC<ImportViewProps> = ({ onEtlComplete }) => {
  const [files, setFiles] = useState<Record<FileType, FileState>>({
    dit: { file: null, parsed: null, loading: false },
    sample: { file: null, parsed: null, loading: false },
    order: { file: null, parsed: null, loading: false },
  });

  const [isProcessing, setIsProcessing] = useState(false);
  const [processingStep, setProcessingStep] = useState('');
  const [error, setError] = useState<string | null>(null);

  const fileInputRefs = {
    dit: useRef<HTMLInputElement>(null),
    sample: useRef<HTMLInputElement>(null),
    order: useRef<HTMLInputElement>(null),
  };

  const handleFileSelect = async (type: FileType, file: File) => {
    setFiles(prev => ({
      ...prev,
      [type]: { ...prev[type], file, loading: true }
    }));
    setError(null);

    try {
      const parsed = await etlApi.upload(file, type);
      setFiles(prev => ({
        ...prev,
        [type]: { file, parsed, loading: false }
      }));
    } catch (error: any) {
      console.error(`Error uploading ${type} file:`, error);
      setFiles(prev => ({
        ...prev,
        [type]: { ...prev[type], parsed: null, loading: false }
      }));

      const msg = error.code === 'ECONNABORTED'
        ? '上傳逾時，檔案可能過大，請稍後再試'
        : (error.response?.data?.detail || error.message || '上傳失敗');
      setError(msg);
    }
  };

  const allFilesReady = files.dit.parsed && files.sample.parsed && files.order.parsed;

  const runEtl = async () => {
    if (!allFilesReady) {
      alert("請先上傳所有檔案！");
      return;
    }

    setError(null);
    setIsProcessing(true);
    const steps = [
      "正在匯入 DIT Report...",
      "正在匯入 樣品紀錄...",
      "正在匯入 訂單明細...",
      "執行資料標準化 (Normalization)...",
      "執行模糊比對 (Fuzzy Matching)...",
      "運算完成！"
    ];

    try {
      for (let i = 0; i < steps.length - 2; i++) {
        setProcessingStep(steps[i]);
        if (i === 0 && files.dit.parsed) {
          await etlApi.import(files.dit.parsed.file_id);
        } else if (i === 1 && files.sample.parsed) {
          await etlApi.import(files.sample.parsed.file_id);
        } else if (i === 2 && files.order.parsed) {
          await etlApi.import(files.order.parsed.file_id);
        }
        await new Promise(resolve => setTimeout(resolve, 500));
      }

      setProcessingStep(steps[4]);
      await matchApi.run();

      setProcessingStep(steps[5]);
      await new Promise(resolve => setTimeout(resolve, 500));

      onEtlComplete();
    } catch (error: any) {
      console.error('ETL error:', error);
      const msg = error.response?.data?.detail || error.message || 'ETL 處理失敗，請檢查檔案格式';
      setError(msg);
    } finally {
      setIsProcessing(false);
    }
  };


  const fileConfigs = [
    { type: 'dit' as FileType, title: '1. DIT Report', desc: '含 Metadata (前16行)' },
    { type: 'sample' as FileType, title: '2. 樣品紀錄', desc: '含檔頭 (前9行)' },
    { type: 'order' as FileType, title: '3. 訂單明細', desc: '標準格式' },
  ];

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <div className="flex justify-between items-end">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">原始資料匯入中心</h1>
          <p className="text-slate-500 mt-1">系統將自動偵測 Excel/CSV 檔頭位置並進行智慧欄位對應。</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={async () => {
              if (confirm('確定要清除所有已上傳的資料與分析結果嗎？')) {
                try {
                  await etlApi.clearData();
                  setFiles({
                    dit: { file: null, parsed: null, loading: false },
                    sample: { file: null, parsed: null, loading: false },
                    order: { file: null, parsed: null, loading: false },
                  });
                  // Reset file inputs
                  Object.values(fileInputRefs).forEach(ref => {
                    if (ref.current) ref.current.value = '';
                  });
                  setError(null);
                  setProcessingStep('');
                  // Reload page to refresh other components if needed, or just notify parent
                  window.location.reload();
                } catch (err) {
                  console.error(err);
                  setError('清除資料失敗');
                }
              }
            }}
            className="flex items-center gap-2 px-4 py-3 rounded-lg text-red-600 bg-red-50 hover:bg-red-100 font-bold border border-red-200 transition-all"
          >
            <RefreshCw size={18} />
            清除 Data
          </button>
          <button
            onClick={runEtl}
            disabled={isProcessing || !allFilesReady}
            className={`flex items-center gap-2 px-6 py-3 rounded-lg text-white font-bold shadow-lg transition-all ${isProcessing || !allFilesReady
              ? 'bg-slate-400 cursor-not-allowed shadow-none'
              : 'bg-indigo-600 hover:bg-indigo-700 hover:scale-105 shadow-indigo-200'
              }`}
          >
            {isProcessing ? (
              <>
                <RefreshCw size={18} className="animate-spin" />
                運算中...
              </>
            ) : (
              <>
                <Activity size={18} />
                開始 ETL 運算
              </>
            )}
          </button>
        </div>
      </div>

      {isProcessing && (
        <div className="bg-slate-800 text-green-400 font-mono p-4 rounded-lg text-sm shadow-inner">
          <p className="flex items-center gap-2">
            <span className="animate-pulse">▶</span> {processingStep}
          </p>
        </div>
      )}

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg text-sm shadow-sm animate-in fade-in duration-300">
          <p className="flex items-center gap-2 font-bold">
            <span className="text-red-500">⚠</span> 錯誤：{error}
          </p>
          <p className="mt-1 text-xs opacity-80">請檢查檔案格式或連線狀態，並重新嘗試。</p>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {fileConfigs.map(({ type, title, desc }) => {
          const fileState = files[type];
          const isLoaded = !!fileState.parsed;

          return (
            <Card
              key={type}
              className={`p-6 border-dashed border-2 transition-colors cursor-pointer hover:border-indigo-300 ${isLoaded ? 'border-emerald-300 bg-emerald-50/30' : 'border-slate-300'
                }`}
              onClick={() => fileInputRefs[type].current?.click()}
            >
              <input
                ref={fileInputRefs[type]}
                type="file"
                accept=".xlsx,.xls,.csv"
                className="hidden"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) handleFileSelect(type, file);
                }}
              />
              <div className="flex justify-between items-start mb-4">
                <div className={`p-3 rounded-lg ${isLoaded ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-500'
                  }`}>
                  {fileState.loading ? (
                    <RefreshCw size={24} className="animate-spin" />
                  ) : isLoaded ? (
                    <CheckCircle size={24} />
                  ) : (
                    <FileText size={24} />
                  )}
                </div>
                {isLoaded && <Badge type="success">Ready</Badge>}
              </div>
              <h3 className="text-lg font-bold text-slate-800">{title}</h3>
              <p className="text-xs text-slate-500 font-mono mt-1 mb-3 truncate">
                {fileState.file?.name || "點擊上傳..."}
              </p>
              <p className="text-sm text-slate-600">{desc}</p>

              {fileState.parsed && (
                <div className="mt-4 pt-3 border-t border-slate-200/60 flex justify-between text-sm">
                  <span className="text-slate-500">預覽筆數</span>
                  <span className="font-bold font-mono text-slate-700">
                    {fileState.parsed.row_count} 筆
                  </span>
                </div>
              )}
            </Card>
          );
        })}
      </div>

      {allFilesReady && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 animate-in fade-in slide-in-from-bottom-2 duration-500">
          <Card className="overflow-hidden">
            <div className="bg-slate-50 px-4 py-3 border-b border-slate-200 flex justify-between items-center">
              <h3 className="font-bold text-slate-700 text-sm flex items-center gap-2">
                <Database size={16} />
                DIT 解析結果 (預覽)
              </h3>
              <Badge type="info">Auto-Skipped Header</Badge>
            </div>
            <table className="w-full text-xs text-left">
              <thead className="bg-white text-slate-500 border-b border-slate-200">
                <tr>
                  <th className="px-4 py-2">Customer</th>
                  <th className="px-4 py-2">Part No</th>
                  <th className="px-4 py-2">Stage</th>
                  <th className="px-4 py-2 text-right">EAU</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {(files.dit.parsed?.preview as unknown as DitRecord[] || []).slice(0, 5).map((row, i) => (
                  <tr key={i} className="hover:bg-slate-50">
                    <td className="px-4 py-2 font-medium text-slate-700">{row.customer}</td>
                    <td className="px-4 py-2 font-mono text-slate-500">{row.pn}</td>
                    <td className="px-4 py-2 text-slate-600">{row.stage}</td>
                    <td className="px-4 py-2 text-right font-mono">{row.eau?.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <Card className="overflow-hidden">
            <div className="bg-slate-50 px-4 py-3 border-b border-slate-200 flex justify-between items-center">
              <h3 className="font-bold text-slate-700 text-sm flex items-center gap-2">
                <Database size={16} />
                訂單解析結果 (預覽)
              </h3>
              <Badge type="info">Detected CP950</Badge>
            </div>
            <table className="w-full text-xs text-left">
              <thead className="bg-white text-slate-500 border-b border-slate-200">
                <tr>
                  <th className="px-4 py-2">Customer</th>
                  <th className="px-4 py-2">Part No</th>
                  <th className="px-4 py-2">Status</th>
                  <th className="px-4 py-2 text-right">Qty / Kpcs</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {(files.order.parsed?.preview as unknown as OrderRecord[] || []).slice(0, 5).map((row, i) => (
                  <tr key={i} className="hover:bg-slate-50">
                    <td className="px-4 py-2 font-medium text-slate-700">{row.customer}</td>
                    <td className="px-4 py-2 font-mono text-slate-500">{row.pn}</td>
                    <td className="px-4 py-2">
                      <span className={`px-1.5 py-0.5 rounded text-[10px] ${row.status === 'Shipped' ? 'bg-green-100 text-green-700' : 'bg-pink-100 text-pink-700'
                        }`}>
                        {row.status}
                      </span>
                    </td>
                    <td className="px-4 py-2 text-right font-mono">{row.qty?.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      )}
    </div>
  );
};
