import { useRef, useState, useEffect } from 'react';
import html2pdf from 'html2pdf.js';
import * as echarts from 'echarts';
import { Download, Upload, RefreshCw, FileSpreadsheet, CheckCircle2, AlertCircle, Server } from 'lucide-react';
import { CoverPage } from './components/CoverPage';
import { Page02Industry } from './components/Page02Industry';
import { Page03Duration } from './components/Page03Duration';
import { Page04Portrait } from './components/Page04Portrait';
import { Page05Risk } from './components/Page05Risk';
import { Page06ExportTax } from './components/Page06ExportTax';
import { Page07Association } from './components/Page07Association';
import { BackCover } from './components/BackCover';
import { defaultReportData } from './data/defaultData';
import { parseExcelReportData, generateExcelTemplate } from './utils/excelUtils';
import type { ReportData } from './types/data';

function App() {
  const reportRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [reportData, setReportData] = useState<ReportData>(defaultReportData);
  const [showImport, setShowImport] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [importStatus, setImportStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [isServerGenerating, setIsServerGenerating] = useState(false);

  // 暴露给 Puppeteer 的接口
  useEffect(() => {
    window.loadServerData = (data: ReportData) => {
      console.log('Received data from server injection');
      setReportData(data);
    };

    // 标记页面已加载，但还没准备好（需要等待图表渲染）
    window.isReportReady = false;

    // 检测是否是打印模式
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('print')) {
      document.body.classList.add('print-mode');
    }

    return () => {
      delete window.loadServerData;
    };
  }, []);

  // 监听数据变化，设置渲染完成信号
  useEffect(() => {
    // 给 ECharts 一点渲染时间
    const timer = setTimeout(() => {
      window.isReportReady = true;
      console.log('Report is ready for capture');
    }, 2000);

    return () => {
      clearTimeout(timer);
      window.isReportReady = false;
    };
  }, [reportData]);

  const handleDownloadPDF = async () => {
    console.log('开始生成报告...');
    const element = reportRef.current;
    if (!element) {
      console.error('报告元素未找到');
      alert('无法找到报告内容，请刷新页面重试');
      return;
    }
    console.log('找到报告元素');

    try {
      // 1. 切换到导出状态样式
      console.log('应用导出样式...');
      element.classList.add('is-exporting');

      // 强制重绘
      element.getBoundingClientRect();
      await new Promise(resolve => setTimeout(resolve, 300));

      // 2. 处理图表：将 ECharts 转换为图片
      console.log('处理图表...');
      const chartContainers = element.querySelectorAll('.echarts-canvas-container');
      console.log(`找到 ${chartContainers.length} 个图表容器`);

      const chartPromises = Array.from(chartContainers).map(async (container, index) => {
        const inner = container.querySelector('.echarts-inner');
        const exportImg = container.querySelector('.echarts-export-image') as HTMLImageElement;

        if (inner && exportImg) {
          try {
            // 尝试获取图表实例
            const instance = echarts.getInstanceByDom(inner as HTMLElement);

            if (instance) {
              const imgUrl = instance.getDataURL({
                pixelRatio: 2,
                backgroundColor: '#fff',
                type: 'png'
              });
              exportImg.src = imgUrl;
              console.log(`图表 ${index} 转换成功`);
            } else {
              console.warn(`图表 ${index} 实例未找到，使用透明占位`);
              exportImg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
            }
          } catch (error) {
            console.error(`图表 ${index} 转换失败:`, error);
            exportImg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
          }
        }
      });

      await Promise.all(chartPromises);
      console.log('图表处理完成');

      // 3. 等待短暂时间让图片显示
      await new Promise(resolve => setTimeout(resolve, 500));

      // 4. 生成 PDF
      console.log('开始生成PDF...');
      const opt = {
        margin: 0,
        filename: `${reportData.companyName}_运营报告_${new Date().toLocaleDateString()}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        enableLinks: false,
        html2canvas: {
          scale: 2,
          useCORS: true,
          logging: false,
          width: 794,
          windowWidth: 794,
          scrollY: 0,
          letterRendering: true,
          backgroundColor: '#ffffff',
          onclone: (clonedDoc: Document) => {
            // 在克隆的文档中确保所有图片都显示
            const imgs = clonedDoc.querySelectorAll('img');
            imgs.forEach((img: HTMLImageElement) => {
              if (img.style.display === 'none') {
                img.style.display = 'block';
              }
            });
          }
        },
        jsPDF: { unit: 'px', format: [794, 1123], orientation: 'portrait' },
        pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
      };

      // 显示加载提示
      alert('正在生成PDF，请稍候...这可能需要几秒钟时间。');

      // @ts-expect-error - html2pdf call signature
      await html2pdf().set(opt).from(element).save();
      console.log('PDF生成成功');
      alert('PDF生成成功！文件已开始下载。');

    } catch (error) {
      console.error('PDF导出失败:', error);
      alert(`PDF生成失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      // 5. 恢复原始样式
      console.log('恢复原始样式...');
      element.classList.remove('is-exporting');
    }
  };

  const handleServerGenerate = async () => {
    setIsServerGenerating(true);
    try {
      const response = await fetch('/api/generate-pdf', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(reportData),
      });

      if (!response.ok) {
        throw new Error(`Server responded with ${response.status}`);
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportData.companyName}_运营报告_服务端_${new Date().toLocaleDateString()}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      alert('服务端生成 PDF 成功！');
    } catch (error) {
      console.error('Server PDF generation failed:', error);
      alert(`服务端生成失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsServerGenerating(false);
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsImporting(true);
    setImportStatus('idle');

    try {
      const newData = await parseExcelReportData(file);
      setReportData(newData);
      setImportStatus('success');
      setTimeout(() => {
        setShowImport(false);
        setImportStatus('idle');
      }, 1500);
    } catch (err) {
      console.error('Import failed:', err);
      setImportStatus('error');
    } finally {
      setIsImporting(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 flex font-sans relative overflow-x-hidden">

      {/* Control Panel (Sidebar) */}
      <div className={`fixed left-0 top-0 h-full bg-white shadow-2xl z-[60] transition-all duration-300 no-print flex flex-col ${showImport ? 'w-[380px]' : 'w-0 overflow-hidden'}`}>
        <div className="p-8 flex flex-col h-full w-[380px]">
          <div className="flex items-center justify-between mb-8">
            <h3 className="text-xl font-bold text-gray-800 flex items-center gap-2">
              <Upload size={22} className="text-blue-600" />
              数据导入中心
            </h3>
            <button onClick={() => setShowImport(false)} className="text-gray-400 hover:text-gray-600 transition-colors text-2xl">&times;</button>
          </div>

          <div className="bg-blue-50 border border-blue-100 rounded-xl p-5 mb-8">
            <h4 className="text-sm font-bold text-blue-800 mb-2 flex items-center gap-2">
              <FileSpreadsheet size={16} />
              第一步：准备数据
            </h4>
            <p className="text-xs text-blue-600 mb-4 leading-relaxed">
              请使用我们提供的专用 Excel 模板填充真实业务数据。模板中包含 13 个页签（Sheet），图表描述请在“图表描述”页签维护。
            </p>
            <button
              onClick={generateExcelTemplate}
              className="w-full bg-white border border-blue-200 text-blue-600 hover:bg-blue-50 py-2.5 rounded-lg text-xs font-bold flex items-center justify-center gap-2 transition-all shadow-sm"
            >
              <Download size={14} />
              下载 Excel 导入模板
            </button>
          </div>

          <div className="flex-grow">
            <h4 className="text-sm font-bold text-gray-700 mb-4 flex items-center gap-2">
              <RefreshCw size={16} className={isImporting ? 'animate-spin' : ''} />
              第二步：上传文件
            </h4>

            <div
              onClick={() => fileInputRef.current?.click()}
              className={`border-2 border-dashed rounded-xl p-10 flex flex-col items-center justify-center cursor-pointer transition-all ${
                importStatus === 'success' ? 'border-green-400 bg-green-50' :
                importStatus === 'error' ? 'border-red-400 bg-red-50' :
                'border-gray-200 hover:border-blue-400 hover:bg-blue-50'
              }`}
            >
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileUpload}
                className="hidden"
                accept=".xlsx, .xls"
              />

              {isImporting ? (
                <div className="flex flex-col items-center animate-pulse">
                  <RefreshCw size={40} className="text-blue-500 animate-spin mb-3" />
                  <span className="text-sm text-blue-600 font-medium">解析数据中...</span>
                </div>
              ) : importStatus === 'success' ? (
                <div className="flex flex-col items-center text-green-600">
                  <CheckCircle2 size={40} className="mb-3" />
                  <span className="text-sm font-bold">导入成功！</span>
                </div>
              ) : importStatus === 'error' ? (
                <div className="flex flex-col items-center text-red-600">
                  <AlertCircle size={40} className="mb-3" />
                  <span className="text-sm font-bold">导入失败，请检查模板</span>
                </div>
              ) : (
                <>
                  <Upload size={40} className="text-gray-300 mb-3" />
                  <span className="text-sm text-gray-500 font-medium">点击或拖拽 Excel 文件</span>
                  <span className="text-[10px] text-gray-400 mt-2">支持 .xlsx, .xls 格式</span>
                </>
              )}
            </div>
          </div>

          <div className="mt-auto pt-8 border-t border-gray-100 text-center">
            <p className="text-[10px] text-gray-400">
              泾渭云数据报告系统 v2.0
            </p>
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="fixed bottom-10 right-10 z-50 flex flex-col gap-3 no-print">
        <button
          onClick={() => setShowImport(!showImport)}
          className="bg-white hover:bg-gray-50 text-blue-600 font-bold py-3 px-8 rounded-full shadow-2xl flex items-center gap-2 transition-all transform hover:scale-105 border border-blue-100 active:scale-95"
        >
          <Upload size={20} />
          数据导入
        </button>

        {/* <button
          onClick={handleDownloadPDF}
          className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-full shadow-2xl flex items-center gap-2 transition-all transform hover:scale-105 active:scale-95"
        >
          <Download size={20} />
          浏览器生成
        </button> */}

        <button
          onClick={handleServerGenerate}
          disabled={isServerGenerating}
          className="bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white font-bold py-3 px-8 rounded-full shadow-2xl flex items-center gap-2 transition-all transform hover:scale-105 active:scale-95"
        >
          {isServerGenerating ? <RefreshCw size={20} className="animate-spin" /> : <Server size={20} />}
          导出 PDF
        </button>
      </div>

      {/* Main Display Area - Fluid Content */}
      <div className={`flex-1 flex flex-col transition-all duration-300 ${showImport ? 'pl-[380px]' : ''}`}>
        <div
          ref={reportRef}
          className="bg-white shadow-2xl overflow-hidden print:overflow-visible print:shadow-none w-full"
        >
          <CoverPage data={reportData} />
          <Page02Industry mapData={reportData.mapData} tableData={reportData.regionStatistics} />
          <Page03Duration durationData={reportData.durationStatistics} funnelData={reportData.funnelData} />
          <Page04Portrait data={reportData.sunburstData} poorCustomerData={reportData.poorCustomerData} goodCustomerData={reportData.goodCustomerData} allDescription={reportData.portraitDescriptions?.all} poorDescription={reportData.portraitDescriptions?.poor} goodDescription={reportData.portraitDescriptions?.good} />
           <Page05Risk riskData={reportData.riskIndicators} />
           <Page06ExportTax exportFreeTaxRebate={reportData.exportFreeTaxRebate} exportTaxRebate={reportData.exportTaxRebate} chartDescriptions={reportData.chartDescriptions} />
           <Page07Association loginPersonAssociation={reportData.loginPersonAssociation} legalPersonAssociation={reportData.legalPersonAssociation} chartDescriptions={reportData.chartDescriptions} />
           <BackCover riskScanning={reportData.riskScanning} riskScanningDescription={reportData.chartDescriptions?.riskScanning} />
         </div>
       </div>

    </div>
  );
}

export default App;
