'use client';

import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, LineChart, Line } from 'recharts';
import { BarChart3, PieChart as PieChartIcon, Target, TrendingUp } from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

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

export default function AnalysisCharts({ state, dispatch }: AnalysisChartsProps) {
  // 准备图表数据
  const scoreDistributionData = [
    { range: '0-20分', count: state.analysisResults.filter(r => r.overallScore < 20).length, color: '#dc2626' },
    { range: '20-40分', count: state.analysisResults.filter(r => r.overallScore >= 20 && r.overallScore < 40).length, color: '#ea580c' },
    { range: '40-60分', count: state.analysisResults.filter(r => r.overallScore >= 40 && r.overallScore < 60).length, color: '#f59e0b' },
    { range: '60-80分', count: state.analysisResults.filter(r => r.overallScore >= 60 && r.overallScore < 80).length, color: '#22c55e' },
    { range: '80-100分', count: state.analysisResults.filter(r => r.overallScore >= 80).length, color: '#16a34a' }
  ].filter(item => item.count > 0);

  const factorPerformanceData = state.factors
    .filter(f => f.enabled)
    .map(factor => ({
      name: factor.name,
      weight: Math.round(factor.weight * 100),
      category: factor.category
    }))
    .sort((a, b) => b.weight - a.weight);

  const categoryPerformanceData = [
    {
      category: '土壤条件',
      avgScore: state.analysisResults.length > 0
        ? Math.round(state.analysisResults.reduce((sum, r) => sum + r.soilScore, 0) / state.analysisResults.length)
        : 0,
      weight: Math.round(state.weightConfig.soil * 100)
    },
    {
      category: '气候条件',
      avgScore: state.analysisResults.length > 0
        ? Math.round(state.analysisResults.reduce((sum, r) => sum + r.climateScore, 0) / state.analysisResults.length)
        : 0,
      weight: Math.round(state.weightConfig.climate * 100)
    },
    {
      category: '地形条件',
      avgScore: state.analysisResults.length > 0
        ? Math.round(state.analysisResults.reduce((sum, r) => sum + r.topographyScore, 0) / state.analysisResults.length)
        : 0,
      weight: Math.round(state.weightConfig.topography * 100)
    },
    {
      category: '基础设施',
      avgScore: state.analysisResults.length > 0
        ? Math.round(state.analysisResults.reduce((sum, r) => sum + r.infrastructureScore, 0) / state.analysisResults.length)
        : 0,
      weight: Math.round(state.weightConfig.infrastructure * 100)
    }
  ];

  const cropRecommendationData = state.analysisResults
    .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.avgScore = Math.round((existing.avgScore + rec.suitabilityScore) / 2);
      } else {
        acc.push({
          crop: rec.crop.name,
          frequency: 1,
          avgScore: rec.suitabilityScore,
          category: rec.crop.category
        });
      }
      return acc;
    }, [] as any[])
    .sort((a, b) => b.frequency - a.frequency)
    .slice(0, 10);

  const economicReturnData = state.analysisResults
    .map(result => {
      const block = state.landBlocks.find(b => b.id === result.blockId);
      return {
        name: result.blockName,
        returnPerAcre: result.economicReturn && block?.area
          ? Math.round(result.economicReturn / block.area)
          : 0,
        totalReturn: result.economicReturn || 0,
        score: result.overallScore
      };
    })
    .sort((a, b) => b.returnPerAcre - a.returnPerAcre);

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8', '#82CA9D'];

  if (state.analysisResults.length === 0) {
    return (
      <Card className="p-8 text-center">
        <BarChart3 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>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      <Tabs defaultValue="distribution" className="space-y-4">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="distribution" className="flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            得分分布
          </TabsTrigger>
          <TabsTrigger value="factors" className="flex items-center gap-2">
            <Target className="w-4 h-4" />
            因子分析
          </TabsTrigger>
          <TabsTrigger value="crops" className="flex items-center gap-2">
            <TrendingUp className="w-4 h-4" />
            作物推荐
          </TabsTrigger>
          <TabsTrigger value="economic" className="flex items-center gap-2">
            <PieChartIcon className="w-4 h-4" />
            经济效益
          </TabsTrigger>
          <TabsTrigger value="comparison" className="flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            对比分析
          </TabsTrigger>
        </TabsList>

        {/* 得分分布 */}
        <TabsContent value="distribution" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">得分分布直方图</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={scoreDistributionData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="range" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="count" fill="#8884d8">
                    {scoreDistributionData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">等级分布饼图</h3>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={scoreDistributionData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ range, count }) => `${range}: ${count}个`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="count"
                  >
                    {scoreDistributionData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 因子分析 */}
        <TabsContent value="factors" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">评价因子权重分布</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={factorPerformanceData} layout="horizontal">
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis type="number" />
                  <YAxis dataKey="name" type="category" width={80} />
                  <Tooltip />
                  <Bar dataKey="weight" fill="#8884d8" />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">各维度得分对比</h3>
              <ResponsiveContainer width="100%" height={300}>
                <RadarChart data={categoryPerformanceData}>
                  <PolarGrid />
                  <PolarAngleAxis dataKey="category" />
                  <PolarRadiusAxis angle={90} domain={[0, 100]} />
                  <Radar name="平均得分" dataKey="avgScore" stroke="#8884d8" fill="#8884d8" fillOpacity={0.6} />
                  <Radar name="权重" dataKey="weight" stroke="#82ca9d" fill="#82ca9d" fillOpacity={0.6} />
                  <Tooltip />
                </RadarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 作物推荐 */}
        <TabsContent value="crops" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">作物推荐频率</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={cropRecommendationData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="crop" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="frequency" fill="#00C49F" />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">作物适宜性得分</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={cropRecommendationData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="crop" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="avgScore" fill="#FFBB28" />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 经济效益 */}
        <TabsContent value="economic" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">地块亩均收益</h3>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={economicReturnData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="returnPerAcre" fill="#8884d8" />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="text-lg font-medium mb-4">得分与收益相关性</h3>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={economicReturnData.sort((a, b) => a.score - b.score)}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="score" />
                  <YAxis />
                  <Tooltip />
                  <Line type="monotone" dataKey="returnPerAcre" stroke="#8884d8" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 对比分析 */}
        <TabsContent value="comparison" className="space-y-4">
          <Card className="p-6">
            <h3 className="text-lg font-medium mb-4">地块综合对比</h3>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={state.analysisResults.map(result => ({
                name: result.blockName,
                综合得分: result.overallScore,
                土壤得分: Math.round(result.soilScore),
                气候得分: Math.round(result.climateScore),
                地形得分: Math.round(result.topographyScore),
                基础设施得分: Math.round(result.infrastructureScore)
              }))}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="综合得分" fill="#8884d8" />
                <Bar dataKey="土壤得分" fill="#00C49F" />
                <Bar dataKey="气候得分" fill="#FFBB28" />
                <Bar dataKey="地形得分" fill="#FF8042" />
                <Bar dataKey="基础设施得分" fill="#8884d8" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}