'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { toast } from 'sonner';
import {
  Settings,
  SlidersHorizontal,
  TrendingUp,
  Target,
  Droplet,
  Sun,
  Mountain,
  Building,
  RefreshCw
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

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

export default function FactorWeights({ state, dispatch }: FactorWeightsProps) {
  const totalWeight = Math.round(
    (state.weightConfig.soil + state.weightConfig.climate +
     state.weightConfig.topography + state.weightConfig.infrastructure) * 100
  );

  const handleWeightChange = (category: keyof SpatialAnalysisState['weightConfig'], value: number[]) => {
    dispatch({
      type: 'SET_WEIGHT_CONFIG',
      payload: {
        ...state.weightConfig,
        [category]: value[0]
      }
    });
  };

  const handleResetWeights = () => {
    dispatch({ type: 'RESET_WEIGHTS' });
    toast.success('权重配置已重置为默认值');
  };

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

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

  const factorCategories = [
    {
      key: 'soil' as const,
      name: '土壤因子',
      icon: <Target className="w-5 h-5 text-amber-600" />,
      description: 'pH值、有机质、全氮、全磷、全钾、土壤质地等',
      factors: state.factors.filter(f => f.category === 'soil')
    },
    {
      key: 'climate' as const,
      name: '气候因子',
      icon: <Sun className="w-5 h-5 text-blue-600" />,
      description: '年均温度、年降雨量、日照时数、无霜期等',
      factors: state.factors.filter(f => f.category === 'climate')
    },
    {
      key: 'topography' as const,
      name: '地形因子',
      icon: <Mountain className="w-5 h-5 text-green-600" />,
      description: '海拔高度、坡度、坡向、地貌类型等',
      factors: state.factors.filter(f => f.category === 'topography')
    },
    {
      key: 'infrastructure' as const,
      name: '基础设施因子',
      icon: <Building className="w-5 h-5 text-purple-600" />,
      description: '灌溉条件、交通便利性、排水条件等',
      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-blue-100 dark:bg-blue-900 rounded-lg">
            <SlidersHorizontal className="w-5 h-5 text-blue-600 dark:text-blue-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={totalWeight === 100 ? "default" : "destructive"}
            className="px-3 py-1"
          >
            总权重: {totalWeight}%
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={handleResetWeights}
          >
            <RefreshCw className="w-4 h-4 mr-2" />
            重置
          </Button>
        </div>
      </div>

      {/* 权重配置区域 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        {factorCategories.map((category) => (
          <div
            key={category.key}
            className={`p-4 rounded-lg border-2 ${getWeightColor(category.key)}`}
          >
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-3">
                {getWeightIcon(category.key)}
                <div>
                  <h4 className="font-medium">{category.name}</h4>
                  <p className="text-xs text-muted-foreground mt-1">
                    {category.description}
                  </p>
                </div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold">
                  {Math.round(state.weightConfig[category.key] * 100)}%
                </div>
                <div className="text-xs text-muted-foreground">
                  {category.factors.length} 个因子
                </div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span>权重调整</span>
                <span>{Math.round(state.weightConfig[category.key] * 100)}%</span>
              </div>
              <Slider
                value={[state.weightConfig[category.key] * 100]}
                onValueChange={(value) => handleWeightChange(category.key, value)}
                max={60}
                min={5}
                step={5}
                className="w-full"
                disabled={state.isBatchAnalyzing}
              />
              <Progress
                value={state.weightConfig[category.key] * 100}
                className="h-2"
              />
            </div>

            {/* 显示该类别下的主要因子 */}
            <div className="mt-4 pt-4 border-t border-current/20">
              <div className="text-xs font-medium mb-2">主要评价因子：</div>
              <div className="flex flex-wrap gap-1">
                {category.factors.slice(0, 3).map((factor) => (
                  <Badge
                    key={factor.id}
                    variant="outline"
                    className="text-xs px-2 py-0.5"
                  >
                    {factor.name}
                  </Badge>
                ))}
                {category.factors.length > 3 && (
                  <Badge variant="outline" className="text-xs px-2 py-0.5">
                    +{category.factors.length - 3}
                  </Badge>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 权重总和警告 */}
      {totalWeight !== 100 && (
        <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-start gap-3">
            <TrendingUp 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">
                所有因子权重总和必须为100%才能进行批量分析。
                当前总和为 {totalWeight}%，{totalWeight > 100 ? '超出' : '还差'} {Math.abs(totalWeight - 100)}%。
              </p>
              <p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
                💡 建议权重分配：土壤因子(35%)、气候因子(30%)、地形因子(20%)、基础设施因子(15%)
              </p>
            </div>
          </div>
        </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">
          <Settings className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <h4 className="font-medium text-blue-800 dark:text-blue-200">
              权重配置说明
            </h4>
            <ul className="text-sm text-blue-700 dark:text-blue-300 mt-2 space-y-1">
              <li>• <strong>土壤因子</strong>：反映地块基础肥力和物理化学性质</li>
              <li>• <strong>气候因子</strong>：决定光热水的匹配度和作物适应性</li>
              <li>• <strong>地形因子</strong>：影响水土保持和机械化作业条件</li>
              <li>• <strong>基础设施因子</strong>：体现生产条件和集约化水平</li>
            </ul>
            <p className="text-xs text-blue-600 dark:text-blue-400 mt-3">
              权重配置将直接影响最终适宜性指数的计算结果，请根据实际生产需求科学分配。
            </p>
          </div>
        </div>
      </div>
    </Card>
  );
}