import { useState, useEffect } from 'react';
import jsPDF from 'jspdf';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Checkbox } from '../ui/checkbox';
import { Progress } from '../ui/progress';
import {
  Download,
  FileText,
  BarChart3,
  TrendingUp,
  MapPin,
  Sprout,
  Target,
  AlertCircle,
  CheckCircle2,
  Plus,
  X,
  Radar,
  Map as MapIcon,
  FileDown,
  Lightbulb,
  ArrowRight,
  Scale,
  Zap,
  Clock,
  Eye,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  RadarChart,
  Radar as RechartsRadar,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  ResponsiveContainer,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  LineChart,
  Line,
} from 'recharts';

interface FieldComparisonProps {
  activePath?: string;
}

interface FieldData {
  id: string;
  name: string;
  area: number;
  location: string;
  soilType: string;
  ph: number;
  organicMatter: number;
  nitrogen: number;
  phosphorus: number;
  potassium: number;
  soilDepth: number;
  slope: number;
  currentCrop: string;
  yield: number;
  suitabilityScore: number;
  suitabilityGrade: '高度适宜' | '一般适宜' | '不适宜';
  irrigation: string;
  drainage: string;
}

interface ComparisonReport {
  id: string;
  name: string;
  generatedTime: string;
  comparedFields: string[];
  fieldData: FieldData[];
}

export function FieldComparison({ activePath }: FieldComparisonProps) {
  const [activeTab, setActiveTab] = useState('indicator');
  const [selectedFields, setSelectedFields] = useState<string[]>(['field-1', 'field-2']);
  const [reportGenerating, setReportGenerating] = useState(false);
  const [reportProgress, setReportProgress] = useState(0);
  const [savedReports, setSavedReports] = useState<ComparisonReport[]>([
    {
      id: 'report-1',
      name: '东区1号地 vs 西区2号地对比分析',
      generatedTime: '2024-10-15 14:35:22',
      comparedFields: ['东区1号地', '西区2号地'],
      fieldData: [],
    },
    {
      id: 'report-2',
      name: '东区1号地 vs 西区2号地 vs 南区3号地对比分析',
      generatedTime: '2024-10-14 09:20:15',
      comparedFields: ['东区1号地', '西区2号地', '南区3号地'],
      fieldData: [],
    },
  ]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/indicator')) {
        setActiveTab('indicator');
      } else if (activePath.includes('/chart')) {
        setActiveTab('chart');
      } else if (activePath.includes('/report')) {
        setActiveTab('report');
      }
    }
  }, [activePath]);

  // 模拟地块数据
  const fieldsData: FieldData[] = [
    {
      id: 'field-1',
      name: '东区1号地',
      area: 50.5,
      location: '东经120.15°, 北纬30.25°',
      soilType: '壤土',
      ph: 6.5,
      organicMatter: 32,
      nitrogen: 1.8,
      phosphorus: 1.2,
      potassium: 18,
      soilDepth: 85,
      slope: 3,
      currentCrop: '水稻',
      yield: 750,
      suitabilityScore: 87,
      suitabilityGrade: '高度适宜',
      irrigation: '喷灌',
      drainage: '良好',
    },
    {
      id: 'field-2',
      name: '西区2号地',
      area: 45.2,
      location: '东经120.12°, 北纬30.28°',
      soilType: '粘土',
      ph: 7.8,
      organicMatter: 22,
      nitrogen: 1.3,
      phosphorus: 0.9,
      potassium: 14,
      soilDepth: 55,
      slope: 5,
      currentCrop: '玉米',
      yield: 650,
      suitabilityScore: 72,
      suitabilityGrade: '一般适宜',
      irrigation: '滴灌',
      drainage: '中等',
    },
    {
      id: 'field-3',
      name: '南区3号地',
      area: 38.8,
      location: '东经120.18°, 北纬30.22°',
      soilType: '砂土',
      ph: 8.5,
      organicMatter: 15,
      nitrogen: 0.8,
      phosphorus: 0.6,
      potassium: 10,
      soilDepth: 42,
      slope: 8,
      currentCrop: '小麦',
      yield: 480,
      suitabilityScore: 58,
      suitabilityGrade: '不适宜',
      irrigation: '漫灌',
      drainage: '较差',
    },
    {
      id: 'field-4',
      name: '北区4号地',
      area: 55.0,
      location: '东经120.20°, 北纬30.30°',
      soilType: '壤土',
      ph: 6.8,
      organicMatter: 28,
      nitrogen: 1.6,
      phosphorus: 1.0,
      potassium: 16,
      soilDepth: 75,
      slope: 2,
      currentCrop: '大豆',
      yield: 380,
      suitabilityScore: 82,
      suitabilityGrade: '高度适宜',
      irrigation: '喷灌',
      drainage: '良好',
    },
  ];

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

  const handleAddField = (fieldId: string) => {
    if (selectedFields.length >= 4) {
      toast.error('最多只能同时对比4个地块');
      return;
    }
    setSelectedFields([...selectedFields, fieldId]);
  };

  const handleRemoveField = (fieldId: string) => {
    if (selectedFields.length <= 2) {
      toast.error('至少需要选择2个地块进行对比');
      return;
    }
    setSelectedFields(selectedFields.filter(id => id !== fieldId));
  };

  const handleGenerateReport = () => {
    setReportGenerating(true);
    setReportProgress(0);

    const interval = setInterval(() => {
      setReportProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setReportGenerating(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,
          };
          
          setSavedReports(prev => [newReport, ...prev]);
          toast.success('对比分析报告已生成！');
          setActiveTab('report');
          return 100;
        }
        return prev + 10;
      });
    }, 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文档
      const doc = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      });

      // 设置字体（支持中文）
      doc.setFont('helvetica');
      let yPosition = 20;

      // 标题
      doc.setFontSize(20);
      doc.text('地块对比分析报告', 105, yPosition, { align: 'center' });
      yPosition += 15;

      // 报告信息
      doc.setFontSize(10);
      doc.text(`生成时间: ${reportData.generatedTime}`, 20, yPosition);
      yPosition += 7;
      doc.text(`对比地块: ${reportData.comparedFields.join('、')}`, 20, yPosition);
      yPosition += 15;

      // 执行摘要
      doc.setFontSize(14);
      doc.text('执行摘要', 20, yPosition);
      yPosition += 10;

      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];

      doc.setFontSize(10);
      doc.text(`最优地块: ${bestField?.name || 'N/A'} (综合评分: ${bestField?.suitabilityScore || 0})`, 25, yPosition);
      yPosition += 7;
      doc.text(`最高产量: ${highestYield?.name || 'N/A'} (${highestYield?.yield || 0} kg/亩)`, 25, yPosition);
      yPosition += 7;
      doc.text(`最佳有机质: ${bestOrganic?.name || 'N/A'} (${bestOrganic?.organicMatter || 0} g/kg)`, 25, yPosition);
      yPosition += 15;

      // 详细数据表格
      doc.setFontSize(14);
      doc.text('详细数据对比', 20, yPosition);
      yPosition += 10;

      // 表格标题
      doc.setFontSize(9);
      const headers = ['地块名称', '面积(亩)', 'pH', '有机质(g/kg)', '产量(kg/亩)', '适宜性'];
      const colWidth = 30;
      headers.forEach((header, i) => {
        doc.text(header, 20 + i * colWidth, yPosition);
      });
      yPosition += 7;

      // 表格数据
      fields.forEach((field) => {
        if (yPosition > 270) {
          doc.addPage();
          yPosition = 20;
        }
        doc.text(field.name, 20, yPosition);
        doc.text(field.area.toString(), 50, yPosition);
        doc.text(field.ph.toString(), 80, yPosition);
        doc.text(field.organicMatter.toString(), 110, yPosition);
        doc.text(field.yield.toString(), 140, yPosition);
        doc.text(field.suitabilityGrade, 170, yPosition);
        yPosition += 7;
      });

      yPosition += 10;

      // 分析结论
      if (yPosition > 250) {
        doc.addPage();
        yPosition = 20;
      }
      doc.setFontSize(14);
      doc.text('智能分析结论', 20, yPosition);
      yPosition += 10;

      doc.setFontSize(10);
      const analyses = [
        `根据对比分析，${bestField?.name}综合适宜性最高，建议优先发展。`,
        `${highestYield?.name}产量表现最优，可作为高产示范田。`,
        `${bestOrganic?.name}有机质含量最佳，土壤肥力较好。`,
      ];

      analyses.forEach((analysis) => {
        if (yPosition > 270) {
          doc.addPage();
          yPosition = 20;
        }
        doc.text(`• ${analysis}`, 25, yPosition);
        yPosition += 7;
      });

      // 保存PDF
      const fileName = `${reportData.name}_${reportData.generatedTime.replace(/:/g, '-').replace(/\//g, '-')}.pdf`;
      doc.save(fileName);
      
      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>

          <h2>改进建议</h2>
          ${fields.map(field => {
            const suggestions = [];
            if (field.ph < 6.0 || field.ph > 7.5) {
              suggestions.push(field.ph < 6.0 
                ? '施用石灰或碱性肥料提高pH值至6.0-7.5' 
                : '施用硫磺或酸性肥料降低pH值至6.0-7.5');
            }
            if (field.organicMatter < 25) {
              suggestions.push('增施有机肥，提高有机质含量至25 g/kg以上');
            }
            if (field.soilDepth < 60) {
              suggestions.push('进行深耕深松，改善土层厚度');
            }
            if (suggestions.length === 0) {
              suggestions.push('土壤条件良好，继续保持现有管理措施');
            }
            return `
              <div class="analysis">
                <p><strong>${field.name}</strong></p>
                ${suggestions.map(s => `<p>  • ${s}</p>`).join('')}
              </div>
            `;
          }).join('')}

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

      // 创建Blob并下载
      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) => {
    setSavedReports(prev => prev.filter(r => r.id !== reportId));
    toast.success('报告已删除');
  };

  const getGradeColor = (grade: string) => {
    switch (grade) {
      case '高度适宜': return 'bg-green-500 text-white';
      case '一般适宜': return 'bg-yellow-500 text-white';
      case '不适宜': return 'bg-red-500 text-white';
      default: return 'bg-gray-500 text-white';
    }
  };

  // 雷达图数据
  const radarData = [
    {
      indicator: 'pH值',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.ph / 10) * 100,
      }), {}),
    },
    {
      indicator: '有机质',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.organicMatter / 40) * 100,
      }), {}),
    },
    {
      indicator: '全氮',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.nitrogen / 2.5) * 100,
      }), {}),
    },
    {
      indicator: '全磷',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.phosphorus / 2.0) * 100,
      }), {}),
    },
    {
      indicator: '全钾',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.potassium / 25) * 100,
      }), {}),
    },
    {
      indicator: '土层厚度',
      ...comparisonFields.reduce((acc, field) => ({
        ...acc,
        [field.name]: (field.soilDepth / 100) * 100,
      }), {}),
    },
  ];

  // 产量对比数据
  const yieldData = comparisonFields.map(field => ({
    name: field.name,
    产量: field.yield,
    有机质: field.organicMatter,
  }));

  // 养分对比数据
  const nutrientData = comparisonFields.map(field => ({
    name: field.name,
    全氮: field.nitrogen,
    全磷: field.phosphorus,
    全钾: field.potassium,
  }));

  // 生成智能分析结论
  const generateAnalysis = () => {
    const analyses: string[] = [];
    
    // 对比产量和有机质
    const sortedByYield = [...comparisonFields].sort((a, b) => b.yield - a.yield);
    const highestYield = sortedByYield[0];
    const lowestYield = sortedByYield[sortedByYield.length - 1];
    
    if (highestYield.organicMatter > lowestYield.organicMatter) {
      const diff = ((highestYield.organicMatter - lowestYield.organicMatter) / lowestYield.organicMatter * 100).toFixed(1);
      analyses.push(
        `${highestYield.name}产量高于${lowestYield.name}，主要原因是其有机质含量高出${diff}%，建议${lowestYield.name}增施有机肥。`
      );
    }

    // 对比pH值
    const acidFields = comparisonFields.filter(f => f.ph < 6.0);
    const alkalineFields = comparisonFields.filter(f => f.ph > 7.5);
    
    if (acidFields.length > 0) {
      analyses.push(
        `${acidFields.map(f => f.name).join('、')}的pH值偏低，建议施用石灰或碱性肥料改良。`
      );
    }
    
    if (alkalineFields.length > 0) {
      analyses.push(
        `${alkalineFields.map(f => f.name).join('、')}的pH值偏高，建议施用硫磺或酸性肥料降低pH值。`
      );
    }

    // 对比土层厚度
    const shallowFields = comparisonFields.filter(f => f.soilDepth < 60);
    if (shallowFields.length > 0) {
      analyses.push(
        `${shallowFields.map(f => f.name).join('、')}的土层厚度不足，建议进行深耕深松，提高土壤蓄水保肥能力。`
      );
    }

    // 对比适宜性
    const highSuitability = comparisonFields.filter(f => f.suitabilityScore >= 80);
    const lowSuitability = comparisonFields.filter(f => f.suitabilityScore < 60);
    
    if (highSuitability.length > 0 && lowSuitability.length > 0) {
      analyses.push(
        `${highSuitability.map(f => f.name).join('、')}综合适宜性较高，可优先种植高价值经济作物；${lowSuitability.map(f => f.name).join('、')}需要进行系统改良。`
      );
    }

    return analyses;
  };

  const smartAnalyses = generateAnalysis();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">地块对比分析</h2>
          <p className="text-muted-foreground">
            多维度指标看板、可视化图表分析与智能对比报告
          </p>
        </div>
      </div>

      {/* 地块选择器 */}
      <Card className="p-4">
        <div className="flex items-start gap-4">
          <div className="flex-1">
            <label className="text-xs text-muted-foreground mb-2 block">选择对比地块 (2-4个)</label>
            <div className="flex flex-wrap gap-2">
              {comparisonFields.map(field => (
                <Badge
                  key={field.id}
                  className="bg-green-100 text-green-800 px-3 py-1.5 flex items-center gap-2"
                >
                  {field.name}
                  <button
                    onClick={() => handleRemoveField(field.id)}
                    className="hover:bg-green-200 rounded-full p-0.5"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </Badge>
              ))}
              {availableFields.length > 0 && (
                <Select onValueChange={handleAddField}>
                  <SelectTrigger className="w-40">
                    <div className="flex items-center gap-2">
                      <Plus className="w-4 h-4" />
                      <span>添加地块</span>
                    </div>
                  </SelectTrigger>
                  <SelectContent>
                    {availableFields.map(field => (
                      <SelectItem key={field.id} value={field.id}>
                        {field.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
          </div>
          <div className="flex-shrink-0">
            <label className="text-xs text-muted-foreground mb-2 block opacity-0">操作</label>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={handleGenerateReport}
              disabled={reportGenerating}
            >
              <FileText className="w-4 h-4 mr-2" />
              生成报告
            </Button>
          </div>
        </div>
        
        {reportGenerating && (
          <div className="mt-4 pt-4 border-t">
            <div className="flex items-center justify-between text-sm mb-2">
              <span className="text-muted-foreground">生成进度</span>
              <span className="font-medium">{reportProgress}%</span>
            </div>
            <Progress value={reportProgress} className="h-2" />
            <p className="text-xs text-muted-foreground text-center mt-2">
              正在生成报告，请稍候...
            </p>
          </div>
        )}
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="indicator">多维度指标看板</TabsTrigger>
          <TabsTrigger value="chart">可视化图表分析</TabsTrigger>
          <TabsTrigger value="report">对比报告生成</TabsTrigger>
        </TabsList>

        {/* 多维度指标看板 */}
        <TabsContent value="indicator" className="space-y-4">
          {/* 基础属性对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <MapPin className="w-5 h-5 text-blue-600" />
              基础属性对比
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">指标项</th>
                    {comparisonFields.map(field => (
                      <th key={field.id} className="px-4 py-3 text-center text-xs">
                        {field.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">面积 (亩)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.area}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">位置</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.location}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">土壤类型</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.soilType}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">坡度 (°)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.slope}
                      </td>
                    ))}
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>

          {/* 自然条件对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Sprout className="w-5 h-5 text-green-600" />
              自然条件对比
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">指标项</th>
                    {comparisonFields.map(field => (
                      <th key={field.id} className="px-4 py-3 text-center text-xs">
                        {field.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">pH值</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <div className="flex items-center justify-center gap-2">
                          <span className="text-sm">{field.ph}</span>
                          {field.ph >= 6.0 && field.ph <= 7.5 ? (
                            <CheckCircle2 className="w-4 h-4 text-green-500" />
                          ) : (
                            <AlertCircle className="w-4 h-4 text-yellow-500" />
                          )}
                        </div>
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">有机质 (g/kg)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <div className="flex items-center justify-center gap-2">
                          <span className="text-sm">{field.organicMatter}</span>
                          {field.organicMatter >= 25 ? (
                            <CheckCircle2 className="w-4 h-4 text-green-500" />
                          ) : (
                            <AlertCircle className="w-4 h-4 text-yellow-500" />
                          )}
                        </div>
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">全氮 (g/kg)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.nitrogen}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">全磷 (g/kg)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.phosphorus}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">全钾 (g/kg)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.potassium}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">土层厚度 (cm)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <div className="flex items-center justify-center gap-2">
                          <span className="text-sm">{field.soilDepth}</span>
                          {field.soilDepth >= 60 ? (
                            <CheckCircle2 className="w-4 h-4 text-green-500" />
                          ) : (
                            <AlertCircle className="w-4 h-4 text-yellow-500" />
                          )}
                        </div>
                      </td>
                    ))}
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>

          {/* 经营现状对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <BarChart3 className="w-5 h-5 text-purple-600" />
              经营现状对比
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">指标项</th>
                    {comparisonFields.map(field => (
                      <th key={field.id} className="px-4 py-3 text-center text-xs">
                        {field.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">当前作物</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        <Badge variant="outline">{field.currentCrop}</Badge>
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">产量 (kg/亩)</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <span className="text-sm font-medium text-green-600">
                          {field.yield}
                        </span>
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">灌溉方式</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.irrigation}
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">排水状况</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center text-sm">
                        {field.drainage}
                      </td>
                    ))}
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>

          {/* 评价结果对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Target className="w-5 h-5 text-orange-600" />
              适宜性评价对比
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">指标项</th>
                    {comparisonFields.map(field => (
                      <th key={field.id} className="px-4 py-3 text-center text-xs">
                        {field.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-4 py-3 text-sm font-medium">综合评分</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <span className="text-xl font-medium text-green-600">
                          {field.suitabilityScore}
                        </span>
                      </td>
                    ))}
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium">适宜性等级</td>
                    {comparisonFields.map(field => (
                      <td key={field.id} className="px-4 py-3 text-center">
                        <Badge className={getGradeColor(field.suitabilityGrade)}>
                          {field.suitabilityGrade}
                        </Badge>
                      </td>
                    ))}
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>

        {/* 可视化图表分析 */}
        <TabsContent value="chart" className="space-y-4">
          {/* 雷达图 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Radar className="w-5 h-5 text-blue-600" />
              多维度雷达图对比
            </h3>
            <p className="text-sm text-muted-foreground mb-4">
              综合展示各地块在多个指标上的相对优劣势
            </p>
            <div className="h-96">
              <ResponsiveContainer width="100%" height="100%">
                <RadarChart data={radarData}>
                  <PolarGrid />
                  <PolarAngleAxis dataKey="indicator" />
                  <PolarRadiusAxis angle={90} domain={[0, 100]} />
                  {comparisonFields.map((field, index) => {
                    const colors = ['#10b981', '#3b82f6', '#f59e0b', '#ef4444'];
                    return (
                      <RechartsRadar
                        key={field.id}
                        name={field.name}
                        dataKey={field.name}
                        stroke={colors[index]}
                        fill={colors[index]}
                        fillOpacity={0.3}
                      />
                    );
                  })}
                  <Legend />
                </RadarChart>
              </ResponsiveContainer>
            </div>
          </Card>

          {/* 产量与有机质对比 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-green-600" />
                产量对比 (kg/亩)
              </h3>
              <div className="h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={yieldData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="产量" fill="#10b981" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-purple-600" />
                有机质含量对比 (g/kg)
              </h3>
              <div className="h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={yieldData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="有机质" fill="#8b5cf6" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </div>

          {/* 养分对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Scale className="w-5 h-5 text-orange-600" />
              土壤养分对比 (g/kg)
            </h3>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={nutrientData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="全氮" stroke="#10b981" strokeWidth={2} />
                  <Line type="monotone" dataKey="全磷" stroke="#3b82f6" strokeWidth={2} />
                  <Line type="monotone" dataKey="全钾" stroke="#f59e0b" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </Card>

          {/* 地图对比 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <MapIcon className="w-5 h-5 text-blue-600" />
              地块空间分布对比
            </h3>
            <div className="grid grid-cols-2 gap-4">
              {comparisonFields.map((field, index) => (
                <div key={field.id} className="space-y-2">
                  <h4 className="text-sm font-medium">{field.name}</h4>
                  <div className="h-48 bg-gradient-to-br from-green-100 to-green-200 rounded-lg flex items-center justify-center relative overflow-hidden">
                    <div className="absolute inset-0 opacity-20">
                      <div className="grid grid-cols-8 grid-rows-8 h-full w-full">
                        {Array.from({ length: 64 }).map((_, i) => (
                          <div
                            key={i}
                            className="border border-green-300"
                            style={{
                              backgroundColor: `rgba(34, 197, 94, ${0.1 + (field.suitabilityScore / 100) * 0.6})`,
                            }}
                          />
                        ))}
                      </div>
                    </div>
                    <div className="relative text-center">
                      <MapPin className="w-12 h-12 text-green-600 mx-auto mb-2" />
                      <p className="text-sm font-medium">{field.location}</p>
                      <Badge className={`mt-2 ${getGradeColor(field.suitabilityGrade)}`}>
                        {field.suitabilityGrade}
                      </Badge>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 对比报告生成 */}
        <TabsContent value="report" className="space-y-4">
          {/* 报告列表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <FileText className="w-5 h-5 text-green-600" />
              历史报告列表
            </h3>
            
            {savedReports.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <FileText className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>暂无保存的报告</p>
                <p className="text-sm mt-1">选择地块后点击"生成报告"创建新报告</p>
              </div>
            ) : (
              <div className="space-y-3">
                {savedReports.map((report) => (
                  <div
                    key={report.id}
                    className="p-4 border rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <h4 className="mb-2 flex items-center gap-2">
                          <FileText className="w-4 h-4 text-green-600" />
                          {report.name}
                        </h4>
                        <div className="flex items-center gap-4 text-sm text-muted-foreground">
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            生成时间: {report.generatedTime}
                          </span>
                          <span className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            对比地块: {report.comparedFields.join('、')}
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                          onClick={() => handleDownloadPDF(report)}
                        >
                          <Download className="w-4 h-4 mr-1" />
                          下载PDF
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                          onClick={() => handleDownloadWord(report)}
                        >
                          <Download className="w-4 h-4 mr-1" />
                          下载Word
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-gray-600 hover:text-gray-700 hover:bg-gray-100"
                          onClick={() => handleDeleteReport(report.id)}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>

          {/* 报告预览 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Eye className="w-5 h-5 text-blue-600" />
              当前对比分析报告预览
            </h3>

            {/* 报告标题 */}
            <div className="mb-6 p-4 bg-gradient-to-r from-green-50 to-blue-50 rounded-lg border-l-4 border-green-600">
              <h2 className="text-green-800 mb-2">地块对比分析报告</h2>
              <p className="text-sm text-muted-foreground">
                预览时间: {new Date().toLocaleString('zh-CN', { 
                  year: 'numeric', 
                  month: '2-digit', 
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')} | 对比地块: {comparisonFields.map(f => f.name).join('、')}
              </p>
            </div>

            {/* 执行摘要 */}
            <div className="mb-6">
              <h4 className="mb-3 flex items-center gap-2">
                <Zap className="w-4 h-4 text-yellow-600" />
                执行摘要
              </h4>
              <div className="grid grid-cols-3 gap-4">
                <div className="p-4 bg-green-50 rounded-lg">
                  <p className="text-xs text-muted-foreground mb-1">最优地块</p>
                  <p className="text-lg font-medium text-green-700">
                    {[...comparisonFields].sort((a, b) => b.suitabilityScore - a.suitabilityScore)[0].name}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    综合评分: {[...comparisonFields].sort((a, b) => b.suitabilityScore - a.suitabilityScore)[0].suitabilityScore}
                  </p>
                </div>
                <div className="p-4 bg-blue-50 rounded-lg">
                  <p className="text-xs text-muted-foreground mb-1">最高产量</p>
                  <p className="text-lg font-medium text-blue-700">
                    {[...comparisonFields].sort((a, b) => b.yield - a.yield)[0].name}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {[...comparisonFields].sort((a, b) => b.yield - a.yield)[0].yield} kg/亩
                  </p>
                </div>
                <div className="p-4 bg-purple-50 rounded-lg">
                  <p className="text-xs text-muted-foreground mb-1">最佳有机质</p>
                  <p className="text-lg font-medium text-purple-700">
                    {[...comparisonFields].sort((a, b) => b.organicMatter - a.organicMatter)[0].name}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {[...comparisonFields].sort((a, b) => b.organicMatter - a.organicMatter)[0].organicMatter} g/kg
                  </p>
                </div>
              </div>
            </div>

            {/* 智能分析结论 */}
            <div className="mb-6">
              <h4 className="mb-3 flex items-center gap-2">
                <Lightbulb className="w-4 h-4 text-yellow-600" />
                智能分析结论
              </h4>
              <div className="space-y-3">
                {smartAnalyses.map((analysis, index) => (
                  <div key={index} className="p-4 bg-blue-50 border-l-4 border-blue-600 rounded-r-lg">
                    <p className="text-sm text-blue-900 flex items-start gap-2">
                      <ArrowRight className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <span>{analysis}</span>
                    </p>
                  </div>
                ))}
              </div>
            </div>

            {/* 改��建议 */}
            <div className="mb-6">
              <h4 className="mb-3 flex items-center gap-2">
                <Target className="w-4 h-4 text-green-600" />
                改进建议
              </h4>
              <div className="space-y-3">
                {comparisonFields.map(field => {
                  const suggestions: string[] = [];
                  
                  if (field.ph < 6.0 || field.ph > 7.5) {
                    suggestions.push(
                      field.ph < 6.0
                        ? '施用石灰或碱性肥料提高pH值至6.0-7.5'
                        : '施用硫磺或酸性肥料降低pH值至6.0-7.5'
                    );
                  }
                  
                  if (field.organicMatter < 25) {
                    suggestions.push('增施有机肥，提高有机质含量至25 g/kg以上');
                  }
                  
                  if (field.soilDepth < 60) {
                    suggestions.push('进行深耕深松，改善土层厚度');
                  }
                  
                  if (field.nitrogen < 1.5) {
                    suggestions.push('适量施用氮肥，提高全氮含量');
                  }

                  if (suggestions.length === 0) {
                    suggestions.push('土壤条件良好，继续保持现有管理措施');
                  }

                  return (
                    <div key={field.id} className="p-4 bg-green-50 rounded-lg">
                      <h5 className="text-sm font-medium text-green-800 mb-2">{field.name}</h5>
                      <ul className="space-y-1">
                        {suggestions.map((suggestion, i) => (
                          <li key={i} className="text-sm text-green-700 flex items-start gap-2">
                            <CheckCircle2 className="w-4 h-4 mt-0.5 flex-shrink-0" />
                            <span>{suggestion}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 数据表格 */}
            <div className="mb-6">
              <h4 className="mb-3">详细数据表格</h4>
              <div className="overflow-x-auto">
                <table className="w-full border">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs border">地块名称</th>
                      <th className="px-3 py-2 text-center text-xs border">面积</th>
                      <th className="px-3 py-2 text-center text-xs border">pH</th>
                      <th className="px-3 py-2 text-center text-xs border">有机质</th>
                      <th className="px-3 py-2 text-center text-xs border">产量</th>
                      <th className="px-3 py-2 text-center text-xs border">适宜性</th>
                    </tr>
                  </thead>
                  <tbody>
                    {comparisonFields.map(field => (
                      <tr key={field.id} className="border-t">
                        <td className="px-3 py-2 text-sm border">{field.name}</td>
                        <td className="px-3 py-2 text-center text-sm border">{field.area}亩</td>
                        <td className="px-3 py-2 text-center text-sm border">{field.ph}</td>
                        <td className="px-3 py-2 text-center text-sm border">{field.organicMatter} g/kg</td>
                        <td className="px-3 py-2 text-center text-sm border">{field.yield} kg/亩</td>
                        <td className="px-3 py-2 text-center text-sm border">
                          <Badge className={getGradeColor(field.suitabilityGrade)}>
                            {field.suitabilityGrade}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 图表插入位置 */}
            <div className="mb-6 p-4 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
              <p className="text-sm text-center text-muted-foreground">
                📊 报告中将自动插入雷达图、柱状图等可视化图表
              </p>
            </div>
          </Card>

          {/* 下载当前报告 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="mb-2">下载当前对比报告</h3>
                <p className="text-sm text-muted-foreground">
                  将当前预览的报告导出为PDF或Word格式
                </p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Button
                size="lg"
                className="bg-red-600 hover:bg-red-700"
                onClick={() => handleDownloadPDF()}
              >
                <Download className="w-5 h-5 mr-2" />
                下载PDF报告
              </Button>
              <Button
                size="lg"
                className="bg-blue-600 hover:bg-blue-700"
                onClick={() => handleDownloadWord()}
              >
                <Download className="w-5 h-5 mr-2" />
                下载Word报告
              </Button>
            </div>

            <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm text-blue-900">
                💡 <strong>报告内容包含：</strong>
              </p>
              <ul className="mt-2 text-sm text-blue-800 space-y-1">
                <li>• 执行摘要与关键指标对比</li>
                <li>• 多维度指标对比表格</li>
                <li>• 雷达图、柱状图等可视化图表</li>
                <li>• 基于规则引擎的智能分析结论</li>
                <li>• 针对性改进建议与措施</li>
                <li>• 地块空间分布对比图</li>
              </ul>
            </div>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
