'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  FileText,
  Download,
  Calendar,
  MapPin,
  BarChart3,
  Star,
  AlertTriangle,
  CheckCircle,
  TrendingUp,
  Users
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

interface AnalysisReportProps {
  state: SpatialAnalysisState;
  dispatch: React.Dispatch<SpatialAnalysisAction>;
}

export default function AnalysisReport({ state, dispatch }: AnalysisReportProps) {
  const handleGenerateReport = () => {
    // 生成分析报告
    const reportTitle = `地块适宜性分析报告_${new Date().toLocaleDateString('zh-CN')}`;
    const reportData = generateReportData();

    dispatch({
      type: 'GENERATE_REPORT',
      payload: { title: reportTitle }
    });

    // 设置当前报告
    dispatch({
      type: 'SET_CURRENT_REPORT',
      payload: reportData
    });
  };

  const generateReportData = () => {
    const selectedBlocks = state.landBlocks.filter(b => state.selectedBlocks.includes(b.id));
    const selectedResults = state.analysisResults.filter(r => state.selectedBlocks.includes(r.blockId));

    // 统计推荐作物
    const cropStats = selectedResults
      .flatMap(result => result.recommendedCrops.slice(0, 3))
      .reduce((acc, rec) => {
        const existing = acc.find(item => item.crop === rec.crop.name);
        if (existing) {
          existing.frequency += 1;
          existing.totalScore += rec.suitabilityScore;
          existing.avgScore = Math.round(existing.totalScore / existing.frequency);
        } else {
          acc.push({
            crop: rec.crop.name,
            category: rec.crop.category,
            frequency: 1,
            totalScore: rec.suitabilityScore,
            avgScore: rec.suitabilityScore,
            economicValue: rec.crop.economicValue
          });
        }
        return acc;
      }, [] as any[])
      .sort((a, b) => b.frequency - a.frequency);

    // 风险统计
    const riskStats = {
      low: selectedResults.filter(r => r.overallScore >= 80).length,
      medium: selectedResults.filter(r => r.overallScore >= 60 && r.overallScore < 80).length,
      high: selectedResults.filter(r => r.overallScore < 60).length
    };

    return {
      id: Date.now().toString(),
      title: `地块适宜性分析报告_${new Date().toLocaleDateString('zh-CN')}`,
      createdAt: new Date().toLocaleString('zh-CN'),
      landBlocks: selectedBlocks,
      results: selectedResults,
      factors: state.factors.filter(f => f.enabled),
      weightConfig: state.weightConfig,
      summary: {
        totalBlocks: selectedBlocks.length,
        averageScore: selectedResults.length > 0
          ? Math.round(selectedResults.reduce((sum, r) => sum + r.overallScore, 0) / selectedResults.length)
          : 0,
        topRecommendedCrops: cropStats.slice(0, 5),
        riskDistribution: riskStats,
        totalArea: selectedBlocks.reduce((sum, b) => sum + b.area, 0),
        estimatedProduction: selectedResults.reduce((sum, r) => sum + (r.estimatedYield || 0), 0),
        estimatedRevenue: selectedResults.reduce((sum, r) => sum + (r.economicReturn || 0), 0)
      }
    };
  };

  const handleDownloadReport = () => {
    const report = state.currentReport || generateReportData();

    // 生成HTML报告
    const htmlContent = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${report.title}</title>
    <style>
        body { font-family: 'Microsoft YaHei', sans-serif; margin: 40px; line-height: 1.6; }
        .header { text-align: center; border-bottom: 2px solid #ccc; padding-bottom: 20px; margin-bottom: 30px; }
        .section { margin-bottom: 30px; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; }
        .card { border: 1px solid #ddd; border-radius: 8px; padding: 15px; background: #f9f9f9; }
        .highlight { background: #e8f5e8; border-color: #4caf50; }
        .warning { background: #fff3cd; border-color: #ffc107; }
        .danger { background: #f8d7da; border-color: #dc3545; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: bold; }
        .badge-success { background: #28a745; color: white; }
        .badge-warning { background: #ffc107; color: black; }
        .badge-danger { background: #dc3545; color: white; }
        .progress { width: 100%; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden; }
        .progress-bar { height: 100%; background: #28a745; transition: width 0.3s; }
    </style>
</head>
<body>
    <div class="header">
        <h1>${report.title}</h1>
        <p>生成时间: ${report.createdAt}</p>
    </div>

    <div class="section">
        <h2>执行摘要</h2>
        <div class="grid">
            <div class="card highlight">
                <h3>分析概览</h3>
                <p><strong>地块数量:</strong> ${report.summary.totalBlocks} 个</p>
                <p><strong>总面积:</strong> ${report.summary.totalArea} 亩</p>
                <p><strong>平均得分:</strong> ${report.summary.averageScore} 分</p>
            </div>
            <div class="card">
                <h3>经济效益</h3>
                <p><strong>预估产量:</strong> ${report.summary.estimatedProduction.toLocaleString()} kg</p>
                <p><strong>预估收益:</strong> ¥${report.summary.estimatedRevenue.toLocaleString()}</p>
                <p><strong>亩均收益:</strong> ¥${Math.round(report.summary.estimatedRevenue / report.summary.totalArea)}</p>
            </div>
        </div>
    </div>

    <div class="section">
        <h2>风险分布</h2>
        <div class="grid">
            <div class="card highlight">
                <h3>低风险地块</h3>
                <p class="badge badge-success">${report.summary.riskDistribution.low} 个</p>
                <div class="progress">
                    <div class="progress-bar" style="width: ${(report.summary.riskDistribution.low / report.summary.totalBlocks * 100)}%"></div>
                </div>
            </div>
            <div class="card warning">
                <h3>中等风险地块</h3>
                <p class="badge badge-warning">${report.summary.riskDistribution.medium} 个</p>
                <div class="progress">
                    <div class="progress-bar" style="width: ${(report.summary.riskDistribution.medium / report.summary.totalBlocks * 100)}%; background: #ffc107;"></div>
                </div>
            </div>
            <div class="card danger">
                <h3>高风险地块</h3>
                <p class="badge badge-danger">${report.summary.riskDistribution.high} 个</p>
                <div class="progress">
                    <div class="progress-bar" style="width: ${(report.summary.riskDistribution.high / report.summary.totalBlocks * 100)}%; background: #dc3545;"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="section">
        <h2>推荐作物排名</h2>
        <table>
            <thead>
                <tr>
                    <th>排名</th>
                    <th>作物名称</th>
                    <th>类别</th>
                    <th>推荐频次</th>
                    <th>平均适宜性</th>
                    <th>经济效益</th>
                </tr>
            </thead>
            <tbody>
                ${report.summary.topRecommendedCrops.map((crop, index) => `
                    <tr>
                        <td>${index + 1}</td>
                        <td><strong>${crop.crop}</strong></td>
                        <td>${crop.category}</td>
                        <td>${crop.frequency} 次</td>
                        <td>${crop.avgScore} 分</td>
                        <td>¥${crop.economicValue}/亩</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>

    <div class="section">
        <h2>详细地块分析</h2>
        ${report.results.map(result => {
          const block = report.landBlocks.find(b => b.id === result.blockId);
          return `
            <div class="card" style="margin-bottom: 20px;">
                <h3>${result.blockName}</h3>
                <p><strong>地块信息:</strong> ${block?.area} 亩 | ${block?.soilType} | ${block?.irrigation}</p>
                <p><strong>综合得分:</strong> ${result.overallScore} 分</p>
                <p><strong>推荐作物:</strong> ${result.recommendedCrops.slice(0, 3).map(c => c.crop.name).join('、')}</p>
                <p><strong>风险因素:</strong> ${result.riskFactors.join('；') || '无'}</p>
                <p><strong>改进建议:</strong> ${result.improvementSuggestions.join('；')}</p>
            </div>
          `;
        }).join('')}
    </div>

    <div class="section">
        <h2>分析说明</h2>
        <div class="card">
            <h3>评价方法</h3>
            <p>本次分析采用多因子综合评价法，考虑土壤条件、气候条件、地形条件和基础设施四个维度。</p>
            <p><strong>权重配置:</strong></p>
            <ul>
                <li>土壤条件: ${Math.round(report.weightConfig.soil * 100)}%</li>
                <li>气候条件: ${Math.round(report.weightConfig.climate * 100)}%</li>
                <li>地形条件: ${Math.round(report.weightConfig.topography * 100)}%</li>
                <li>基础设施: ${Math.round(report.weightConfig.infrastructure * 100)}%</li>
            </ul>
        </div>
    </div>

    <div class="section" style="text-align: center; color: #666; font-size: 12px;">
        <p>本报告由智慧农业生产管理系统自动生成</p>
        <p>生成时间: ${new Date().toLocaleString('zh-CN')}</p>
    </div>
</body>
</html>
    `;

    // 下载HTML文件
    const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${state.currentReport?.title || '分析报告'}.html`;
    link.click();
  };

  const currentReport = state.currentReport || generateReportData();

  if (state.analysisResults.length === 0) {
    return (
      <Card className="p-8 text-center">
        <FileText className="w-16 h-16 mx-auto mb-4 text-muted-foreground opacity-50" />
        <h3 className="text-lg font-medium mb-2">暂无分析数据</h3>
        <p className="text-muted-foreground mb-4">
          请先运行分析生成结果
        </p>
        <Button onClick={() => dispatch({ type: 'SET_ACTIVE_TAB', payload: 'overview' })}>
          开始分析
        </Button>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* 报告操作 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <FileText className="w-5 h-5" />
          <h3 className="text-lg font-medium">分析报告</h3>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={handleGenerateReport}>
            <FileText className="w-4 h-4 mr-2" />
            生成报告
          </Button>
          <Button onClick={handleDownloadReport}>
            <Download className="w-4 h-4 mr-2" />
            下载报告
          </Button>
        </div>
      </div>

      {/* 报告概览 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Calendar className="w-5 h-5 text-blue-500" />
          <h4 className="font-medium">{currentReport.title}</h4>
          <Badge variant="outline" className="text-xs">
            {currentReport.createdAt}
          </Badge>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div className="text-2xl font-bold text-blue-600">
              {currentReport.summary.totalBlocks}
            </div>
            <div className="text-sm text-muted-foreground">分析地块</div>
          </div>

          <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
            <div className="text-2xl font-bold text-green-600">
              {currentReport.summary.averageScore}
            </div>
            <div className="text-sm text-muted-foreground">平均得分</div>
          </div>

          <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
            <div className="text-2xl font-bold text-purple-600">
              {currentReport.summary.totalArea}
            </div>
            <div className="text-sm text-muted-foreground">总面积(亩)</div>
          </div>

          <div className="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg">
            <div className="text-2xl font-bold text-orange-600">
              {Math.round(currentReport.summary.estimatedRevenue / 1000)}K
            </div>
            <div className="text-sm text-muted-foreground">预估收益</div>
          </div>
        </div>
      </Card>

      {/* 推荐作物排名 */}
      <Card className="p-6">
        <h4 className="font-medium mb-4 flex items-center gap-2">
          <Star className="w-4 h-4 text-yellow-500" />
          推荐作物排名
        </h4>

        <div className="space-y-3">
          {currentReport.summary.topRecommendedCrops.map((crop, index) => (
            <div key={crop.crop} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg">
              <div className="flex items-center gap-3">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-white font-bold ${
                  index === 0 ? 'bg-yellow-500' :
                  index === 1 ? 'bg-gray-400' :
                  index === 2 ? 'bg-orange-600' :
                  'bg-blue-500'
                }`}>
                  {index + 1}
                </div>
                <div>
                  <div className="font-medium">{crop.crop}</div>
                  <div className="text-sm text-muted-foreground">{crop.category}</div>
                </div>
              </div>

              <div className="flex items-center gap-4">
                <div className="text-right">
                  <div className="text-sm text-muted-foreground">推荐频次</div>
                  <div className="font-medium">{crop.frequency} 次</div>
                </div>
                <div className="text-right">
                  <div className="text-sm text-muted-foreground">适宜性</div>
                  <div className="font-medium">{crop.avgScore} 分</div>
                </div>
                <div className="text-right">
                  <div className="text-sm text-muted-foreground">经济效益</div>
                  <div className="font-medium">¥{crop.economicValue}/亩</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* 风险分析 */}
      <Card className="p-6">
        <h4 className="font-medium mb-4 flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 text-orange-500" />
          风险分析
        </h4>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="p-4 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="font-medium text-green-900 dark:text-green-100">低风险地块</span>
              <Badge className="bg-green-600">{currentReport.summary.riskDistribution.low} 个</Badge>
            </div>
            <Progress value={(currentReport.summary.riskDistribution.low / currentReport.summary.totalBlocks) * 100} className="h-2" />
            <p className="text-sm text-green-800 dark:text-green-200 mt-2">
              综合得分≥80分，适宜种植推荐作物
            </p>
          </div>

          <div className="p-4 bg-yellow-50 dark:bg-yellow-950 border border-yellow-200 dark:border-yellow-800 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="font-medium text-yellow-900 dark:text-yellow-100">中等风险地块</span>
              <Badge className="bg-yellow-600">{currentReport.summary.riskDistribution.medium} 个</Badge>
            </div>
            <Progress value={(currentReport.summary.riskDistribution.medium / currentReport.summary.totalBlocks) * 100} className="h-2" />
            <p className="text-sm text-yellow-800 dark:text-yellow-200 mt-2">
              综合得分60-79分，需要一定改进措施
            </p>
          </div>

          <div className="p-4 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="font-medium text-red-900 dark:text-red-100">高风险地块</span>
              <Badge className="bg-red-600">{currentReport.summary.riskDistribution.high} 个</Badge>
            </div>
            <Progress value={(currentReport.summary.riskDistribution.high / currentReport.summary.totalBlocks) * 100} className="h-2" />
            <p className="text-sm text-red-800 dark:text-red-200 mt-2">
              综合得分&lt;60分，需要重点改进
            </p>
          </div>
        </div>
      </Card>

      {/* 详细分析结果 */}
      <Card className="p-6">
        <h4 className="font-medium mb-4 flex items-center gap-2">
          <BarChart3 className="w-4 h-4 text-blue-500" />
          详细分析结果
        </h4>

        <div className="space-y-4">
          {currentReport.results.map(result => {
            const block = currentReport.landBlocks.find(b => b.id === result.blockId);
            return (
              <div key={result.blockId} className="p-4 border rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <h5 className="font-medium flex items-center gap-2">
                    <MapPin className="w-4 h-4 text-blue-500" />
                    {result.blockName}
                  </h5>
                  <Badge variant="outline">
                    {result.overallScore} 分
                  </Badge>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm mb-3">
                  <div>
                    <span className="text-muted-foreground">面积:</span>
                    <span className="ml-1">{block?.area} 亩</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">土壤:</span>
                    <span className="ml-1">{block?.soilType}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">灌溉:</span>
                    <span className="ml-1">{block?.irrigation}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">预估收益:</span>
                    <span className="ml-1">¥{result.economicReturn?.toLocaleString()}</span>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="font-medium text-green-600">推荐作物:</span>
                    <div className="mt-1">
                      {result.recommendedCrops.slice(0, 3).map((rec, index) => (
                        <Badge key={index} variant="outline" className="mr-2 mb-1">
                          {rec.crop.name} ({rec.suitabilityScore}分)
                        </Badge>
                      ))}
                    </div>
                  </div>

                  <div>
                    <span className="font-medium text-orange-600">风险因素:</span>
                    <div className="mt-1 text-muted-foreground">
                      {result.riskFactors.length > 0 ? result.riskFactors.join('；') : '无'}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* 报告说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <div className="flex gap-2">
          <FileText className="w-5 h-5 text-blue-600 flex-shrink-0" />
          <div className="text-sm text-blue-800 dark:text-blue-200">
            <p className="font-medium mb-2">报告说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• 本报告基于多因子综合评价模型，结合土壤、气候、地形、基础设施等条件进行分析</li>
              <li>• 推荐作物基于各地区的农业实践数据和科学研究成果</li>
              <li>• 经济效益估算仅供参考，实际收益受市场价格、管理水平等多种因素影响</li>
              <li>• 建议结合实地调研和专家意见，制定最终的种植决策方案</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}