'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { toast } from 'sonner';
import {
  Brain,
  Settings,
  Eye,
  EyeOff,
  CheckCircle2,
  XCircle,
  Target,
  Droplet,
  Sun,
  Mountain,
  Building,
  Info
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

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

export default function EvaluationModel({ state, dispatch }: EvaluationModelProps) {
  const handleToggleFactor = (factorId: string) => {
    dispatch({ type: 'TOGGLE_FACTOR', payload: factorId });
    const factor = state.factors.find(f => f.id === factorId);
    if (factor) {
      toast.success(`${factor.name} 已${factor.enabled ? '禁用' : '启用'}`);
    }
  };

  const getFactorIcon = (category: string) => {
    const icons = {
      soil: <Target className="w-4 h-4" />,
      climate: <Sun className="w-4 h-4" />,
      topography: <Mountain className="w-4 h-4" />,
      infrastructure: <Building className="w-4 h-4" />
    };
    return icons[category as keyof typeof icons] || <Settings className="w-4 h-4" />;
  };

  const getFactorCategoryColor = (category: string) => {
    const colors = {
      soil: 'bg-amber-50 border-amber-200 text-amber-700',
      climate: 'bg-blue-50 border-blue-200 text-blue-700',
      topography: 'bg-green-50 border-green-200 text-green-700',
      infrastructure: 'bg-purple-50 border-purple-200 text-purple-700'
    };
    return colors[category as keyof typeof colors] || 'bg-gray-50 border-gray-200 text-gray-700';
  };

  const enabledFactors = state.factors.filter(f => f.enabled);
  const enabledFactorCount = enabledFactors.length;
  const totalFactorCount = state.factors.length;

  const factorCategories = [
    {
      key: 'soil',
      name: '土壤因子',
      icon: <Target className="w-5 h-5 text-amber-600" />,
      factors: state.factors.filter(f => f.category === 'soil')
    },
    {
      key: 'climate',
      name: '气候因子',
      icon: <Sun className="w-5 h-5 text-blue-600" />,
      factors: state.factors.filter(f => f.category === 'climate')
    },
    {
      key: 'topography',
      name: '地形因子',
      icon: <Mountain className="w-5 h-5 text-green-600" />,
      factors: state.factors.filter(f => f.category === 'topography')
    },
    {
      key: 'infrastructure',
      name: '基础设施因子',
      icon: <Building className="w-5 h-5 text-purple-600" />,
      factors: state.factors.filter(f => f.category === 'infrastructure')
    }
  ];

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
            <Brain className="w-5 h-5 text-purple-600 dark:text-purple-400" />
          </div>
          <div>
            <h3 className="text-lg font-medium">评价模型配置</h3>
            <p className="text-sm text-muted-foreground">选择和配置评价因子</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Badge variant="outline" className="px-3 py-1">
            {enabledFactorCount}/{totalFactorCount} 个因子
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              // 启用所有因子
              state.factors.forEach(factor => {
                if (!factor.enabled) {
                  dispatch({ type: 'TOGGLE_FACTOR', payload: factor.id });
                }
              });
              toast.success('已启用所有评价因子');
            }}
          >
            全部启用
          </Button>
        </div>
      </div>

      {/* 评价因子配置区域 */}
      <div className="space-y-6">
        {factorCategories.map((category) => (
          <div key={category.key} className="space-y-3">
            <div className="flex items-center gap-2">
              {category.icon}
              <h4 className="font-medium">{category.name}</h4>
              <Badge variant="outline" className="text-xs">
                {category.factors.filter(f => f.enabled).length}/{category.factors.length}
              </Badge>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {category.factors.map((factor) => (
                <div
                  key={factor.id}
                  className={`p-4 rounded-lg border-2 transition-all ${
                    factor.enabled
                      ? getFactorCategoryColor(factor.category)
                      : 'bg-gray-50 border-gray-200 text-gray-400 opacity-60'
                  }`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        {getFactorIcon(factor.category)}
                        <h5 className="font-medium text-sm">{factor.name}</h5>
                        {factor.enabled ? (
                          <CheckCircle2 className="w-4 h-4 text-green-600" />
                        ) : (
                          <XCircle className="w-4 h-4 text-gray-400" />
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground mb-2">
                        {factor.description}
                      </p>
                      <div className="flex items-center justify-between">
                        <Badge variant="outline" className="text-xs">
                          权重: {Math.round(factor.weight * 100)}%
                        </Badge>
                        <Switch
                          checked={factor.enabled}
                          onCheckedChange={() => handleToggleFactor(factor.id)}
                          disabled={state.isBatchAnalyzing}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* 模型配置说明 */}
      <div className="mt-6 p-4 bg-purple-50 dark:bg-purple-950 border border-purple-200 dark:border-purple-800 rounded-lg">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-purple-600 mt-0.5" />
          <div>
            <h4 className="font-medium text-purple-800 dark:text-purple-200">
              评价模型说明
            </h4>
            <div className="text-sm text-purple-700 dark:text-purple-300 mt-2 space-y-2">
              <p>
                <strong>多因子加权评价模型</strong>采用层次分析法(AHP)和专家评分法，
                结合农业生产实际需求，构建科学的评价指标体系。
              </p>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-3">
                <div>
                  <h5 className="font-medium mb-2">评价因子选择原则：</h5>
                  <ul className="text-xs space-y-1">
                    <li>• <strong>主导性</strong>：选择对作物生长起决定性作用的因子</li>
                    <li>• <strong>独立性</strong>：避免因子间的重复和高度相关性</li>
                    <li>• <strong>可获取性</strong>：确保数据能够准确获取和更新</li>
                    <li>• <strong>稳定性</strong>：优先选择相对稳定的评价因子</li>
                  </ul>
                </div>
                <div>
                  <h5 className="font-medium mb-2">权重确定方法：</h5>
                  <ul className="text-xs space-y-1">
                    <li>• <strong>专家打分</strong>：邀请农业专家进行权重评分</li>
                    <li>• <strong>层次分析</strong>：构建判断矩阵确定权重</li>
                    <li>• <strong>实地验证</strong>：结合实际产量数据校准权重</li>
                    <li>• <strong>动态调整</strong>：根据作物类型和生产目标调整</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 启用因子过少警告 */}
      {enabledFactorCount < 6 && (
        <div className="mt-4 p-4 bg-yellow-50 dark:bg-yellow-950 border border-yellow-200 dark:border-yellow-800 rounded-lg">
          <div className="flex items-start gap-3">
            <Info className="w-5 h-5 text-yellow-600 mt-0.5" />
            <div>
              <h4 className="font-medium text-yellow-800 dark:text-yellow-200">
                评价因子配置建议
              </h4>
              <p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
                当前仅启用了 {enabledFactorCount} 个评价因子，建议至少启用 6-8 个因子以获得更准确的评价结果。
                确保各类别都有代表性因子参与评价。
              </p>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}