'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Settings,
  Sliders,
  CheckCircle,
  XCircle,
  Info
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

interface FactorConfigurationProps {
  state: SpatialAnalysisState;
  dispatch: React.Dispatch<SpatialAnalysisAction>;
  isDialog?: boolean;
}

export default function FactorConfiguration({ state, dispatch, isDialog = false }: FactorConfigurationProps) {
  const categories = [
    { id: 'soil', name: '土壤条件', color: 'blue' },
    { id: 'climate', name: '气候条件', color: 'green' },
    { id: 'topography', name: '地形条件', color: 'orange' },
    { id: 'infrastructure', name: '基础设施', color: 'purple' }
  ];

  const handleToggleFactor = (factorId: string) => {
    dispatch({ type: 'TOGGLE_FACTOR', payload: factorId });
  };

  const handleUpdateWeight = (factorId: string, weight: number) => {
    dispatch({ type: 'UPDATE_FACTOR_WEIGHT', payload: { id: factorId, weight } });
  };

  const handleResetToDefaults = () => {
    // 重置为默认权重
    const defaultWeights = {
      'soil_ph': 0.15,
      'soil_organic_matter': 0.12,
      'soil_nutrients': 0.18,
      'soil_texture': 0.10,
      'temperature': 0.15,
      'rainfall': 0.12,
      'sunlight': 0.10,
      'elevation': 0.08,
      'slope': 0.06,
      'irrigation': 0.12,
      'accessibility': 0.05
    };

    Object.entries(defaultWeights).forEach(([id, weight]) => {
      dispatch({ type: 'UPDATE_FACTOR_WEIGHT', payload: { id, weight } });
    });
  };

  const getTotalWeight = () => {
    return state.factors.reduce((sum, factor) => sum + factor.weight, 0);
  };

  const getCategoryTotal = (categoryId: string) => {
    return state.factors
      .filter(f => f.category === categoryId && f.enabled)
      .reduce((sum, f) => sum + f.weight, 0);
  };

  const categoryColors = {
    soil: 'blue',
    climate: 'green',
    topography: 'orange',
    infrastructure: 'purple'
  };

  const content = (
    <div className="space-y-6">
      {/* 权重总览 */}
      <Card className="p-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium">权重分配总览</h3>
          <div className="flex items-center gap-2">
            <span className="text-sm text-muted-foreground">总权重:</span>
            <Badge variant={Math.abs(getTotalWeight() - 1) < 0.01 ? 'default' : 'destructive'}>
              {Math.round(getTotalWeight() * 100)}%
            </Badge>
            <Button variant="outline" size="sm" onClick={handleResetToDefaults}>
              重置默认
            </Button>
          </div>
        </div>

        <div className="space-y-3">
          {categories.map(category => {
            const totalWeight = getCategoryTotal(category.id);
            return (
              <div key={category.id}>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm font-medium">{category.name}</span>
                  <span className="text-sm text-muted-foreground">
                    {Math.round(totalWeight * 100)}%
                  </span>
                </div>
                <Progress
                  value={totalWeight * 100}
                  className={`h-2 ${
                    category.id === 'soil' ? 'bg-blue-100' :
                    category.id === 'climate' ? 'bg-green-100' :
                    category.id === 'topography' ? 'bg-orange-100' :
                    'bg-purple-100'
                  }`}
                />
              </div>
            );
          })}
        </div>
      </Card>

      {/* 因子详细配置 */}
      <div className="space-y-4">
        {categories.map(category => (
          <Card key={category.id} className="p-4">
            <h3 className="font-medium mb-4 flex items-center gap-2">
              <div className={`w-3 h-3 rounded-full bg-${categoryColors[category.id]}-500`} />
              {category.name}
              <Badge variant="outline" className="text-xs">
                {state.factors.filter(f => f.category === category.id).length} 个因子
              </Badge>
            </h3>

            <div className="space-y-4">
              {state.factors
                .filter(factor => factor.category === category.id)
                .map(factor => (
                  <div key={factor.id} className="border rounded-lg p-4">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h4 className="font-medium">{factor.name}</h4>
                          {factor.enabled ? (
                            <CheckCircle className="w-4 h-4 text-green-500" />
                          ) : (
                            <XCircle className="w-4 h-4 text-gray-400" />
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          {factor.description}
                        </p>
                      </div>

                      <div className="flex items-center gap-3">
                        <div className="text-right">
                          <div className="text-lg font-bold">
                            {Math.round(factor.weight * 100)}%
                          </div>
                          <div className="text-xs text-muted-foreground">权重</div>
                        </div>

                        <Switch
                          checked={factor.enabled}
                          onCheckedChange={() => handleToggleFactor(factor.id)}
                        />
                      </div>
                    </div>

                    {/* 权重调节 */}
                    {factor.enabled && (
                      <div className="space-y-2">
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-muted-foreground">权重调节</span>
                          <span>{Math.round(factor.weight * 100)}%</span>
                        </div>
                        <Slider
                          value={[factor.weight * 100]}
                          onValueChange={([value]) =>
                            handleUpdateWeight(factor.id, value / 100)
                          }
                          max={50}
                          min={0}
                          step={1}
                          className="w-full"
                        />
                      </div>
                    )}
                  </div>
                ))}
            </div>
          </Card>
        ))}
      </div>

      {/* 配置说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <div className="flex gap-2">
          <Info className="w-5 h-5 text-blue-600 flex-shrink-0" />
          <div className="text-sm text-blue-800 dark:text-blue-200">
            <p className="font-medium mb-2">配置说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• 权重总和应保持100%，系统会自动计算各因子的影响程度</li>
              <li>• 启用/禁用因子来控制评价维度，禁用的因子不参与计算</li>
              <li>• 土壤条件、气候条件、地形条件、基础设施为四大评价维度</li>
              <li>• 可以根据具体需求调整各因子的权重，建议咨询农业专家</li>
              <li>• 点击"重置默认"可以恢复到推荐的标准权重配置</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );

  if (isDialog) {
    return (
      <Dialog open={state.showFactorDialog} onOpenChange={() => dispatch({ type: 'TOGGLE_FACTOR_DIALOG' })}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5" />
              评价因子配置
            </DialogTitle>
          </DialogHeader>
          {content}
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-medium">评价因子配置</h3>
        <div className="flex items-center gap-2">
          <Badge variant="outline">
            启用 {state.factors.filter(f => f.enabled).length} / {state.factors.length}
          </Badge>
          <Button variant="outline" size="sm" onClick={handleResetToDefaults}>
            重置默认
          </Button>
        </div>
      </div>

      {content}
    </div>
  );
}