'use client';

import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Eye, Zap, Lightbulb, Target, ArrowRight, CheckCircle2, Download } from 'lucide-react';
import { FieldData } from './reportComparisonReducer';

interface ReportPreviewProps {
  comparisonFields: FieldData[];
  onDownloadPDF: () => void;
  onDownloadWord: () => void;
}

export function ReportPreview({
  comparisonFields,
  onDownloadPDF,
  onDownloadWord
}: ReportPreviewProps) {
  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 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-4">
      {/* 报告预览 */}
      <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 dark:from-green-950 dark:to-blue-950 rounded-lg border-l-4 border-green-600">
          <h2 className="text-green-800 dark:text-green-200 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-1 md:grid-cols-3 gap-4">
            <div className="p-4 bg-green-50 dark:bg-green-950 rounded-lg">
              <p className="text-xs text-muted-foreground mb-1">最优地块</p>
              <p className="text-lg font-medium text-green-700 dark:text-green-300">
                {[...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 dark:bg-blue-950 rounded-lg">
              <p className="text-xs text-muted-foreground mb-1">最高产量</p>
              <p className="text-lg font-medium text-blue-700 dark:text-blue-300">
                {[...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 dark:bg-purple-950 rounded-lg">
              <p className="text-xs text-muted-foreground mb-1">最佳有机质</p>
              <p className="text-lg font-medium text-purple-700 dark:text-purple-300">
                {[...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 dark:bg-blue-950 border-l-4 border-blue-600 rounded-r-lg">
                <p className="text-sm text-blue-900 dark:text-blue-100 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 dark:bg-green-950 rounded-lg">
                  <h5 className="text-sm font-medium text-green-800 dark:text-green-200 mb-2">{field.name}</h5>
                  <ul className="space-y-1">
                    {suggestions.map((suggestion, i) => (
                      <li key={i} className="text-sm text-green-700 dark:text-green-300 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 dark:bg-gray-900">
                <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-muted 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={onDownloadPDF}
          >
            <Download className="w-5 h-5 mr-2" />
            下载PDF报告
          </Button>
          <Button
            size="lg"
            className="bg-blue-600 hover:bg-blue-700"
            onClick={onDownloadWord}
          >
            <Download className="w-5 h-5 mr-2" />
            下载Word报告
          </Button>
        </div>

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