'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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Download,
  CheckCircle,
  AlertTriangle,
  Star,
  TrendingUp,
  BarChart3,
  Filter,
  ArrowUpDown
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

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

export default function AnalysisResults({ state, dispatch }: AnalysisResultsProps) {
  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-green-600';
    if (score >= 60) return 'text-yellow-600';
    return 'text-red-600';
  };

  const getGradeLabel = (score: number) => {
    if (score >= 80) return '高度适宜';
    if (score >= 60) return '一般适宜';
    return '不适宜';
  };

  const getGradeColor = (score: number) => {
    if (score >= 80) return 'bg-green-100 text-green-800';
    if (score >= 60) return 'bg-yellow-100 text-yellow-800';
    return 'bg-red-100 text-red-800';
  };

  // 筛选结果
  const filteredResults = state.analysisResults.filter(result => {
    if (state.filters.scoreRange) {
      const [min, max] = state.filters.scoreRange;
      if (result.overallScore < min || result.overallScore > max) {
        return false;
      }
    }
    return true;
  });

  // 排序结果
  const sortedResults = [...filteredResults].sort((a, b) => {
    let aValue: number, bValue: number;

    switch (state.sortBy) {
      case 'name':
        aValue = a.blockName.charCodeAt(0);
        bValue = b.blockName.charCodeAt(0);
        break;
      case 'area':
        aValue = a.estimatedYield || 0;
        bValue = b.estimatedYield || 0;
        break;
      case 'score':
      default:
        aValue = a.overallScore;
        bValue = b.overallScore;
        break;
    }

    return state.sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
  });

  const exportResults = () => {
    // 导出分析结果为CSV
    const headers = [
      '地块名称', '综合得分', '适宜性等级', '土壤得分', '气候得分', '地形得分', '基础设施得分',
      '推荐作物', '预估产量(kg)', '经济效益(元)', '风险因素', '改进建议'
    ];

    const csvContent = [
      headers.join(','),
      ...sortedResults.map(result => {
        const topCrop = result.recommendedCrops[0];
        const riskFactors = result.riskFactors.join(';') || '无';
        const improvements = result.improvementSuggestions.join(';') || '无';

        return [
          result.blockName,
          result.overallScore,
          getGradeLabel(result.overallScore),
          Math.round(result.soilScore),
          Math.round(result.climateScore),
          Math.round(result.topographyScore),
          Math.round(result.infrastructureScore),
          topCrop ? topCrop.crop.name : '无',
          result.estimatedYield?.toLocaleString() || '',
          result.economicReturn?.toLocaleString() || '',
          riskFactors,
          improvements
        ].join(',');
      })
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `地块适宜性评价结果_${new Date().toLocaleDateString('zh-CN')}.csv`;
    link.click();
  };

  if (state.analysisResults.length === 0) {
    return null;
  }

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-lg font-medium flex items-center gap-2">
            <Star className="w-5 h-5 text-yellow-500" />
            地块适宜性评价结果
          </h3>
          <p className="text-sm text-muted-foreground mt-1">
            共 {sortedResults.length} 个地块的评价结果
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Select value={state.sortBy} onValueChange={(value: 'score' | 'name' | 'area') =>
            dispatch({ type: 'SET_SORT_BY', payload: value })}>
            <SelectTrigger className="w-32">
              <SelectValue placeholder="排序方式" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="score">综合得分</SelectItem>
              <SelectItem value="name">地块名称</SelectItem>
              <SelectItem value="area">预估产量</SelectItem>
            </SelectContent>
          </Select>

          <Button
            variant="outline"
            size="sm"
            onClick={() => dispatch({
              type: 'SET_SORT_ORDER',
              payload: state.sortOrder === 'asc' ? 'desc' : 'asc'
            })}
          >
            <ArrowUpDown className="w-4 h-4 mr-2" />
            {state.sortOrder === 'asc' ? '升序' : '降序'}
          </Button>

          <Button variant="outline" onClick={exportResults}>
            <Download className="w-4 h-4 mr-2" />
            导出结果
          </Button>
        </div>
      </div>

      {/* 统计摘要 */}
      <div className="mb-6 grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
          <div className="text-2xl font-bold text-green-600">
            {sortedResults.filter(r => r.overallScore >= 80).length}
          </div>
          <div className="text-sm text-muted-foreground">高度适宜</div>
        </div>
        <div className="text-center p-4 bg-yellow-50 dark:bg-yellow-950 rounded-lg">
          <div className="text-2xl font-bold text-yellow-600">
            {sortedResults.filter(r => r.overallScore >= 60 && r.overallScore < 80).length}
          </div>
          <div className="text-sm text-muted-foreground">一般适宜</div>
        </div>
        <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
          <div className="text-2xl font-bold text-red-600">
            {sortedResults.filter(r => r.overallScore < 60).length}
          </div>
          <div className="text-sm text-muted-foreground">不适宜</div>
        </div>
        <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
          <div className="text-2xl font-bold text-blue-600">
            {Math.round(
              sortedResults.reduce((sum, r) => sum + r.overallScore, 0) /
              sortedResults.length
            )}
          </div>
          <div className="text-sm text-muted-foreground">平均得分</div>
        </div>
      </div>

      {/* 结果表格 */}
      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-gray-50 dark:bg-gray-900">
              <TableHead className="w-[120px]">地块名称</TableHead>
              <TableHead className="w-[100px] text-center">综合得分</TableHead>
              <TableHead className="w-[100px] text-center">适宜性等级</TableHead>
              <TableHead className="w-[80px] text-center">土壤得分</TableHead>
              <TableHead className="w-[80px] text-center">气候得分</TableHead>
              <TableHead className="w-[80px] text-center">地形得分</TableHead>
              <TableHead className="w-[100px] text-center">基础设施得分</TableHead>
              <TableHead className="w-[120px]">推荐作物</TableHead>
              <TableHead className="w-[100px] text-center">预估产量</TableHead>
              <TableHead className="w-[100px] text-center">经济效益</TableHead>
              <TableHead className="w-[200px]">风险因素</TableHead>
              <TableHead className="w-[200px]">改进建议</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedResults.map((result, index) => {
              const topCrop = result.recommendedCrops[0];
              return (
                <TableRow key={result.blockId} className="hover:bg-gray-50 dark:hover:bg-gray-900">
                  <TableCell className="font-medium">{result.blockName}</TableCell>
                  <TableCell className="text-center">
                    <div className={`text-lg font-bold ${getScoreColor(result.overallScore)}`}>
                      {result.overallScore}
                    </div>
                    <Progress value={result.overallScore} className="w-16 h-2 mt-1" />
                  </TableCell>
                  <TableCell className="text-center">
                    <Badge className={getGradeColor(result.overallScore)}>
                      {getGradeLabel(result.overallScore)}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-blue-600 font-medium">
                      {Math.round(result.soilScore)}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-green-600 font-medium">
                      {Math.round(result.climateScore)}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-orange-600 font-medium">
                      {Math.round(result.topographyScore)}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-purple-600 font-medium">
                      {Math.round(result.infrastructureScore)}
                    </div>
                  </TableCell>
                  <TableCell>
                    {topCrop && (
                      <div>
                        <div className="font-medium">{topCrop.crop.name}</div>
                        <div className="text-xs text-muted-foreground">
                          {topCrop.crop.category}
                        </div>
                      </div>
                    )}
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-sm">
                      <div>{result.estimatedYield?.toLocaleString()} kg</div>
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="text-sm">
                      <div>¥{result.economicReturn?.toLocaleString()}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm text-red-600">
                      {result.riskFactors.length > 0 ? (
                        <div className="max-w-[180px]">
                          {result.riskFactors.join('、')}
                        </div>
                      ) : (
                        <div className="text-green-600">无明显风险</div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm text-blue-600">
                      <div className="max-w-[180px]">
                        {result.improvementSuggestions.join('、')}
                      </div>
                    </div>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>

      {/* 详细统计信息 */}
      <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
        <div className="flex items-start gap-3">
          <BarChart3 className="w-5 h-5 text-blue-600 mt-0.5" />
          <div className="text-sm text-blue-800 dark:text-blue-200">
            <h4 className="font-medium mb-2">统计分析</h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <h5 className="font-medium text-blue-700 dark:text-blue-300 mb-1">得分分布</h5>
                <ul className="text-xs space-y-1">
                  <li>• 高度适宜 (80-100分): {sortedResults.filter(r => r.overallScore >= 80).length} 个地块</li>
                  <li>• 一般适宜 (60-79分): {sortedResults.filter(r => r.overallScore >= 60 && r.overallScore < 80).length} 个地块</li>
                  <li>• 不适宜 (0-59分): {sortedResults.filter(r => r.overallScore < 60).length} 个地块</li>
                </ul>
              </div>
              <div>
                <h5 className="font-medium text-blue-700 dark:text-blue-300 mb-1">经济效益</h5>
                <ul className="text-xs space-y-1">
                  <li>• 总预估产量: {sortedResults.reduce((sum, r) => sum + (r.estimatedYield || 0), 0).toLocaleString()} kg</li>
                  <li>• 总经济效益: ¥{sortedResults.reduce((sum, r) => sum + (r.economicReturn || 0), 0).toLocaleString()}</li>
                  <li>• 平均亩产: {Math.round(sortedResults.reduce((sum, r) => sum + (r.estimatedYield || 0), 0) / sortedResults.length).toLocaleString()} kg</li>
                </ul>
              </div>
              <div>
                <h5 className="font-medium text-blue-700 dark:text-blue-300 mb-1">因子表现</h5>
                <ul className="text-xs space-y-1">
                  <li>• 平均土壤得分: {Math.round(sortedResults.reduce((sum, r) => sum + r.soilScore, 0) / sortedResults.length)} 分</li>
                  <li>• 平均气候得分: {Math.round(sortedResults.reduce((sum, r) => sum + r.climateScore, 0) / sortedResults.length)} 分</li>
                  <li>• 平均地形得分: {Math.round(sortedResults.reduce((sum, r) => sum + r.topographyScore, 0) / sortedResults.length)} 分</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}