'use client';

import { useReducer } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { FileText, Download } from 'lucide-react';
import {
  reportComparisonReducer,
  initialState,
  ReportComparisonState,
  ComparisonReport,
  fieldsData
} from './components/reportComparisonReducer';
import { FieldSelector } from './components/FieldSelector';
import { ReportList } from './components/ReportList';
import { ReportPreview } from './components/ReportPreview';

export default function ReportPage() {
  const [state, dispatch] = useReducer(reportComparisonReducer, initialState);

  const comparisonFields = fieldsData.filter(f => state.selectedFields.includes(f.id));

  const handleAddField = (fieldId: string) => {
    dispatch({ type: 'ADD_FIELD', payload: fieldId });
  };

  const handleRemoveField = (fieldId: string) => {
    dispatch({ type: 'REMOVE_FIELD', payload: fieldId });
  };

  const handleGenerateReport = () => {
    dispatch({ type: 'SET_REPORT_GENERATING', payload: true });
    dispatch({ type: 'SET_REPORT_PROGRESS', payload: 0 });

    let progress = 0;
    const interval = setInterval(() => {
      progress += 10;
      dispatch({ type: 'SET_REPORT_PROGRESS', payload: progress });

      if (progress >= 100) {
        clearInterval(interval);
        dispatch({ type: 'SET_REPORT_GENERATING', payload: false });

        // 保存新报告
        const reportName = comparisonFields.map(f => f.name).join(' vs ') + '对比分析';
        const newReport: ComparisonReport = {
          id: `report-${Date.now()}`,
          name: reportName,
          generatedTime: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-'),
          comparedFields: comparisonFields.map(f => f.name),
          fieldData: comparisonFields,
        };

        dispatch({ type: 'ADD_SAVED_REPORT', payload: newReport });
        toast.success('对比分析报告已生成！');
      }
    }, 200);
  };

  const handleDownloadPDF = async (report?: ComparisonReport) => {
    const reportData = report || {
      name: comparisonFields.map(f => f.name).join(' vs ') + '对比分析',
      generatedTime: new Date().toLocaleString('zh-CN'),
      comparedFields: comparisonFields.map(f => f.name),
      fieldData: comparisonFields,
    };

    toast.info('正在生成PDF报告，请稍候...');

    try {
      // 简化的PDF生成逻辑（实际项目中可使用jsPDF等库）
      const pdfContent = generatePDFContent(reportData);
      downloadFile(pdfContent, `${reportData.name}_${reportData.generatedTime.replace(/:/g, '-').replace(/\//g, '-')}.pdf`, 'application/pdf');
      toast.success('PDF报告已下载！');
    } catch (error) {
      console.error('PDF生成失败:', error);
      toast.error('PDF生成失败，请重试');
    }
  };

  const handleDownloadWord = async (report?: ComparisonReport) => {
    const reportData = report || {
      name: comparisonFields.map(f => f.name).join(' vs ') + '对比分析',
      generatedTime: new Date().toLocaleString('zh-CN'),
      comparedFields: comparisonFields.map(f => f.name),
      fieldData: comparisonFields,
    };

    toast.info('正在生成Word报告，请稍候...');

    try {
      const fields = reportData.fieldData.length > 0 ? reportData.fieldData : comparisonFields;
      const bestField = [...fields].sort((a, b) => b.suitabilityScore - a.suitabilityScore)[0];
      const highestYield = [...fields].sort((a, b) => b.yield - a.yield)[0];
      const bestOrganic = [...fields].sort((a, b) => b.organicMatter - a.organicMatter)[0];

      // 创建HTML格式的Word文档
      const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="UTF-8">
          <style>
            body { font-family: "Microsoft YaHei", Arial, sans-serif; padding: 40px; }
            h1 { text-align: center; color: #2d5016; font-size: 24px; margin-bottom: 30px; }
            h2 { color: #3f7f1f; font-size: 18px; margin-top: 30px; margin-bottom: 15px; border-bottom: 2px solid #3f7f1f; padding-bottom: 5px; }
            .info { margin: 20px 0; color: #666; font-size: 14px; }
            .summary { background: #f0f9ff; padding: 20px; border-left: 4px solid #3f7f1f; margin: 20px 0; }
            .summary-item { margin: 10px 0; }
            table { width: 100%; border-collapse: collapse; margin: 20px 0; }
            th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
            th { background-color: #3f7f1f; color: white; }
            tr:nth-child(even) { background-color: #f9f9f9; }
            .analysis { background: #e8f5e9; padding: 15px; margin: 10px 0; border-radius: 4px; }
            .footer { margin-top: 40px; text-align: center; color: #999; font-size: 12px; }
          </style>
        </head>
        <body>
          <h1>地块对比分析报告</h1>

          <div class="info">
            <p><strong>生成时间：</strong>${reportData.generatedTime}</p>
            <p><strong>对比地块：</strong>${reportData.comparedFields.join('、')}</p>
          </div>

          <h2>执行摘要</h2>
          <div class="summary">
            <div class="summary-item">
              <strong>最优地块：</strong>${bestField?.name || 'N/A'}
              <span style="color: #3f7f1f;">（综合评分: ${bestField?.suitabilityScore || 0}）</span>
            </div>
            <div class="summary-item">
              <strong>最高产量：</strong>${highestYield?.name || 'N/A'}
              <span style="color: #3f7f1f;">（${highestYield?.yield || 0} kg/亩）</span>
            </div>
            <div class="summary-item">
              <strong>最佳有机质：</strong>${bestOrganic?.name || 'N/A'}
              <span style="color: #3f7f1f;">（${bestOrganic?.organicMatter || 0} g/kg）</span>
            </div>
          </div>

          <h2>详细数据对比</h2>
          <table>
            <thead>
              <tr>
                <th>地块名称</th>
                <th>面积(亩)</th>
                <th>土壤类型</th>
                <th>pH值</th>
                <th>有机质(g/kg)</th>
                <th>产量(kg/亩)</th>
                <th>适宜性</th>
              </tr>
            </thead>
            <tbody>
              ${fields.map(field => `
                <tr>
                  <td>${field.name}</td>
                  <td>${field.area}</td>
                  <td>${field.soilType}</td>
                  <td>${field.ph}</td>
                  <td>${field.organicMatter}</td>
                  <td>${field.yield}</td>
                  <td>${field.suitabilityGrade}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>

          <h2>智能分析结论</h2>
          <div class="analysis">
            <p>• 根据对比分析，<strong>${bestField?.name}</strong>综合适宜性最高，建议优先发展。</p>
            <p>• <strong>${highestYield?.name}</strong>产量表现最优，可作为高产示范田。</p>
            <p>• <strong>${bestOrganic?.name}</strong>有机质含量最佳，土壤肥力较好。</p>
          </div>

          <div class="footer">
            <p>智慧农业生产管理系统 - 地块对比分析报告</p>
            <p>本报告由系统自动生成</p>
          </div>
        </body>
        </html>
      `;

      const blob = new Blob(['\ufeff', htmlContent], {
        type: 'application/msword'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportData.name}_${reportData.generatedTime.replace(/:/g, '-').replace(/\//g, '-')}.doc`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      toast.success('Word报告已下载！');
    } catch (error) {
      console.error('Word生成失败:', error);
      toast.error('Word生成失败，请重试');
    }
  };

  const handleDeleteReport = (reportId: string) => {
    dispatch({ type: 'DELETE_REPORT', payload: reportId });
    toast.success('报告已删除');
  };

  const generatePDFContent = (reportData: any) => {
    // 简化的PDF内容生成
    const fields = reportData.fieldData.length > 0 ? reportData.fieldData : comparisonFields;
    const bestField = [...fields].sort((a, b) => b.suitabilityScore - a.suitabilityScore)[0];
    const highestYield = [...fields].sort((a, b) => b.yield - a.yield)[0];

    return `
地块对比分析报告
================

生成时间: ${reportData.generatedTime}
对比地块: ${reportData.comparedFields.join('、')}

执行摘要
--------
最优地块: ${bestField?.name || 'N/A'} (综合评分: ${bestField?.suitabilityScore || 0})
最高产量: ${highestYield?.name || 'N/A'} (${highestYield?.yield || 0} kg/亩)

详细数据
--------
${fields.map(field => `
${field.name}:
- 面积: ${field.area}亩
- pH值: ${field.ph}
- 有机质: ${field.organicMatter} g/kg
- 产量: ${field.yield} kg/亩
- 适宜性: ${field.suitabilityGrade}
`).join('\n')}

分析结论
--------
根据对比分析，${bestField?.name}综合适宜性最高，建议优先发展。
${highestYield?.name}产量表现最优，可作为高产示范田。
    `.trim();
  };

  const downloadFile = (content: string, filename: string, contentType: string) => {
    const blob = new Blob([content], { type: contentType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-200">报告对比生成</h2>
          <p className="text-muted-foreground">
            智能报告生成、多维度对比分析与一键导出
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => handleDownloadPDF()}>
            <FileText className="w-4 h-4 mr-2" />
            快速生成PDF
          </Button>
        </div>
      </div>

      {/* 地块选择器 */}
      <FieldSelector
        state={state}
        onAddField={handleAddField}
        onRemoveField={handleRemoveField}
        onGenerateReport={handleGenerateReport}
        fieldsData={fieldsData}
      />

      {/* 历史报告列表 */}
      <ReportList
        savedReports={state.savedReports}
        onDownloadPDF={handleDownloadPDF}
        onDownloadWord={handleDownloadWord}
        onDeleteReport={handleDeleteReport}
      />

      {/* 报告预览 */}
      <ReportPreview
        comparisonFields={comparisonFields}
        onDownloadPDF={() => handleDownloadPDF()}
        onDownloadWord={() => handleDownloadWord()}
      />
    </div>
  );
}