'use client';

import { useReducer } from 'react';
import { toast } from 'sonner';
import {
  multiDimensionReducer,
  initialState,
  MultiDimensionAction,
  MultiDimensionState,
  FieldData
} from './components/multiDimensionReducer';
import { FieldSelector } from './components/FieldSelector';
import { BasicProperties } from './components/BasicProperties';
import { NaturalConditions } from './components/NaturalConditions';
import { ManagementStatus } from './components/ManagementStatus';
import { SuitabilityEvaluation } from './components/SuitabilityEvaluation';

export default function MultiDimensionPage() {
  const [state, dispatch] = useReducer(multiDimensionReducer, initialState);

  // 获取当前选中的对比地块
  const comparisonFields = state.fieldsData.filter(f => state.selectedFields.includes(f.id));

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

  const handleRemoveField = (fieldId: string) => {
    if (state.selectedFields.length <= 2) {
      toast.error('至少需要选择2个地块进行对比');
      return;
    }
    dispatch({ type: 'REMOVE_FIELD', payload: fieldId });
  };

  // 生成统计分析
  const generateStatistics = () => {
    if (comparisonFields.length === 0) return null;

    const totalArea = comparisonFields.reduce((sum, f) => sum + f.area, 0);
    const avgYield = Math.round(comparisonFields.reduce((sum, f) => sum + f.yield, 0) / comparisonFields.length);
    const avgScore = Math.round(comparisonFields.reduce((sum, f) => sum + f.suitabilityScore, 0) / comparisonFields.length);
    const avgOrganic = Math.round(comparisonFields.reduce((sum, f) => sum + f.organicMatter, 0) / comparisonFields.length);
    const highSuitabilityCount = comparisonFields.filter(f => f.suitabilityGrade === '高度适宜').length;
    const mediumSuitabilityCount = comparisonFields.filter(f => f.suitabilityGrade === '一般适宜').length;
    const lowSuitabilityCount = comparisonFields.filter(f => f.suitabilityGrade === '不适宜').length;

    return {
      totalArea,
      avgYield,
      avgScore,
      avgOrganic,
      highSuitabilityCount,
      mediumSuitabilityCount,
      lowSuitabilityCount,
      bestField: comparisonFields.sort((a, b) => b.suitabilityScore - a.suitabilityScore)[0],
      highestYieldField: comparisonFields.sort((a, b) => b.yield - a.yield)[0],
      bestOrganicField: comparisonFields.sort((a, b) => b.organicMatter - a.organicMatter)[0],
    };
  };

  const statistics = generateStatistics();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-200">多维度指标看板</h2>
          <p className="text-muted-foreground">
            地块基础属性、自然条件、经营现状与适宜性评价的全面对比分析
          </p>
        </div>
      </div>

      {/* 地块选择器 */}
      <FieldSelector
        selectedFields={state.selectedFields}
        fieldsData={state.fieldsData}
        onAddField={handleAddField}
        onRemoveField={handleRemoveField}
      />

      {/* 统计概览 */}
      {statistics && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="p-4 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900 rounded-lg border border-green-200 dark:border-green-800">
            <div className="text-center">
              <p className="text-xs text-muted-foreground mb-2">对比地块总面积</p>
              <p className="text-2xl font-bold text-green-600 dark:text-green-400 mb-1">
                {statistics.totalArea}
              </p>
              <p className="text-xs text-green-700 dark:text-green-300">亩</p>
            </div>
          </div>

          <div className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-950 dark:to-blue-900 rounded-lg border border-blue-200 dark:border-blue-800">
            <div className="text-center">
              <p className="text-xs text-muted-foreground mb-2">平均产量</p>
              <p className="text-2xl font-bold text-blue-600 dark:text-blue-400 mb-1">
                {statistics.avgYield}
              </p>
              <p className="text-xs text-blue-700 dark:text-blue-300">kg/亩</p>
            </div>
          </div>

          <div className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-950 dark:to-purple-900 rounded-lg border border-purple-200 dark:border-purple-800">
            <div className="text-center">
              <p className="text-xs text-muted-foreground mb-2">平均适宜性评分</p>
              <p className="text-2xl font-bold text-purple-600 dark:text-purple-400 mb-1">
                {statistics.avgScore}
              </p>
              <p className="text-xs text-purple-700 dark:text-purple-300">分</p>
            </div>
          </div>

          <div className="p-4 bg-gradient-to-br from-amber-50 to-amber-100 dark:from-amber-950 dark:to-amber-900 rounded-lg border border-amber-200 dark:border-amber-800">
            <div className="text-center">
              <p className="text-xs text-muted-foreground mb-2">平均有机质</p>
              <p className="text-2xl font-bold text-amber-600 dark:text-amber-400 mb-1">
                {statistics.avgOrganic}
              </p>
              <p className="text-xs text-amber-700 dark:text-amber-300">g/kg</p>
            </div>
          </div>
        </div>
      )}

      {/* 适宜性分布统计 */}
      {statistics && (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="p-4 bg-green-50 dark:bg-green-950 rounded-lg border border-green-200 dark:border-green-800">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground mb-1">高度适宜</p>
                <p className="text-xl font-bold text-green-600 dark:text-green-400">
                  {statistics.highSuitabilityCount}
                </p>
              </div>
              <div className="text-3xl text-green-400 opacity-20">📊</div>
            </div>
          </div>

          <div className="p-4 bg-yellow-50 dark:bg-yellow-950 rounded-lg border border-yellow-200 dark:border-yellow-800">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground mb-1">一般适宜</p>
                <p className="text-xl font-bold text-yellow-600 dark:text-yellow-400">
                  {statistics.mediumSuitabilityCount}
                </p>
              </div>
              <div className="text-3xl text-yellow-400 opacity-20">📈</div>
            </div>
          </div>

          <div className="p-4 bg-red-50 dark:bg-red-950 rounded-lg border border-red-200 dark:border-red-800">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground mb-1">不适宜</p>
                <p className="text-xl font-bold text-red-600 dark:text-red-400">
                  {statistics.lowSuitabilityCount}
                </p>
              </div>
              <div className="text-3xl text-red-400 opacity-20">⚠️</div>
            </div>
          </div>
        </div>
      )}

      {/* 详细对比表格 */}
      {comparisonFields.length > 0 && (
        <div className="space-y-6">
          {/* 基础属性对比 */}
          <BasicProperties comparisonFields={comparisonFields} />

          {/* 自然条件对比 */}
          <NaturalConditions comparisonFields={comparisonFields} />

          {/* 经营现状对比 */}
          <ManagementStatus comparisonFields={comparisonFields} />

          {/* 适宜性评价对比 */}
          <SuitabilityEvaluation comparisonFields={comparisonFields} />
        </div>
      )}

      {/* 优秀地块展示 */}
      {statistics && comparisonFields.length > 0 && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="p-4 bg-gradient-to-br from-green-50 to-white dark:from-green-950 dark:to-card rounded-lg border border-green-200 dark:border-green-800">
            <h4 className="text-sm font-medium text-green-800 dark:text-green-200 mb-2">🏆 最优地块</h4>
            <div className="space-y-1">
              <p className="font-medium">{statistics.bestField.name}</p>
              <p className="text-xs text-muted-foreground">综合评分: {statistics.bestField.suitabilityScore}分</p>
              <p className="text-xs text-muted-foreground">产量: {statistics.bestField.yield}kg/亩</p>
            </div>
          </div>

          <div className="p-4 bg-gradient-to-br from-blue-50 to-white dark:from-blue-950 dark:to-card rounded-lg border border-blue-200 dark:border-blue-800">
            <h4 className="text-sm font-medium text-blue-800 dark:text-blue-200 mb-2">🌾 产量冠军</h4>
            <div className="space-y-1">
              <p className="font-medium">{statistics.highestYieldField.name}</p>
              <p className="text-xs text-muted-foreground">产量: {statistics.highestYieldField.yield}kg/亩</p>
              <p className="text-xs text-muted-foreground">评分: {statistics.highestYieldField.suitabilityScore}分</p>
            </div>
          </div>

          <div className="p-4 bg-gradient-to-br from-purple-50 to-white dark:from-purple-950 dark:to-card rounded-lg border border-purple-200 dark:border-purple-800">
            <h4 className="text-sm font-medium text-purple-800 dark:text-purple-200 mb-2">🌱 肥力最佳</h4>
            <div className="space-y-1">
              <p className="font-medium">{statistics.bestOrganicField.name}</p>
              <p className="text-xs text-muted-foreground">有机质: {statistics.bestOrganicField.organicMatter}g/kg</p>
              <p className="text-xs text-muted-foreground">评分: {statistics.bestOrganicField.suitabilityScore}分</p>
            </div>
          </div>
        </div>
      )}

      {/* 空状态 */}
      {comparisonFields.length === 0 && (
        <div className="p-12 bg-card rounded-lg border text-center">
          <div className="text-muted-foreground">
            <p className="text-lg mb-2">暂无对比地块</p>
            <p className="text-sm">
              请先选择2-4个地块进行多维度指标对比分析
            </p>
          </div>
        </div>
      )}
    </div>
  );
}