'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Settings,
  Sliders,
  BarChart3,
  AlertTriangle,
  CheckCircle,
  TrendingUp,
  Info
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

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

export default function AnalysisControlPanel({ state, dispatch }: AnalysisControlPanelProps) {
  const handleQuickAnalysis = () => {
    // 快速分析，使用默认设置
    const allBlocks = state.landBlocks.map(b => b.id);
    dispatch({ type: 'SET_SELECTED_BLOCKS', payload: allBlocks });
    // 触发分析
    setTimeout(() => {
      const event = new CustomEvent('run-analysis');
      window.dispatchEvent(event);
    }, 100);
  };

  const handleResetFilters = () => {
    dispatch({ type: 'RESET_FILTERS' });
  };

  const enabledFactorsCount = state.factors.filter(f => f.enabled).length;
  const totalWeight = state.weightConfig.soil + state.weightConfig.climate +
                     state.weightConfig.topography + state.weightConfig.infrastructure;

  // 获取风险等级
  const getRiskLevel = () => {
    if (state.analysisResults.length === 0) return { level: 'unknown', color: 'gray', text: '未分析' };

    const avgScore = state.analysisResults.reduce((sum, r) => sum + r.overallScore, 0) / state.analysisResults.length;

    if (avgScore >= 80) return { level: 'low', color: 'green', text: '低风险' };
    if (avgScore >= 60) return { level: 'medium', color: 'yellow', text: '中等风险' };
    return { level: 'high', color: 'red', text: '高风险' };
  };

  const riskLevel = getRiskLevel();

  return (
    <div className="space-y-4">
      {/* 分析状态 */}
      <Card className="p-4">
        <h3 className="font-medium mb-4 flex items-center gap-2">
          <BarChart3 className="w-4 h-4" />
          分析状态
        </h3>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">选择地块</span>
            <Badge variant={state.selectedBlocks.length > 0 ? 'default' : 'secondary'}>
              {state.selectedBlocks.length} / {state.landBlocks.length}
            </Badge>
          </div>

          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">评价因子</span>
            <Badge variant="outline">
              {enabledFactorsCount} / {state.factors.length}
            </Badge>
          </div>

          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">分析结果</span>
            <Badge variant={state.analysisResults.length > 0 ? 'default' : 'secondary'}>
              {state.analysisResults.length} 个
            </Badge>
          </div>
        </div>
      </Card>

      {/* 权重配置 */}
      <Card className="p-4">
        <h3 className="font-medium mb-4 flex items-center gap-2">
          <Sliders className="w-4 h-4" />
          权重配置
        </h3>

        <div className="space-y-3">
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm">土壤条件</span>
              <span className="text-sm font-medium">{Math.round(state.weightConfig.soil * 100)}%</span>
            </div>
            <Progress value={state.weightConfig.soil * 100} className="h-2" />
          </div>

          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm">气候条件</span>
              <span className="text-sm font-medium">{Math.round(state.weightConfig.climate * 100)}%</span>
            </div>
            <Progress value={state.weightConfig.climate * 100} className="h-2" />
          </div>

          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm">地形条件</span>
              <span className="text-sm font-medium">{Math.round(state.weightConfig.topography * 100)}%</span>
            </div>
            <Progress value={state.weightConfig.topography * 100} className="h-2" />
          </div>

          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm">基础设施</span>
              <span className="text-sm font-medium">{Math.round(state.weightConfig.infrastructure * 100)}%</span>
            </div>
            <Progress value={state.weightConfig.infrastructure * 100} className="h-2" />
          </div>
        </div>

        <div className="mt-3 pt-3 border-t text-center">
          <span className="text-xs text-muted-foreground">
            总权重: {Math.round(totalWeight * 100)}%
            {Math.abs(totalWeight - 1) > 0.01 && (
              <span className="text-red-500 ml-1">(需调整为100%)</span>
            )}
          </span>
        </div>

        <Button
          variant="outline"
          size="sm"
          className="w-full mt-3"
          onClick={() => dispatch({ type: 'TOGGLE_WEIGHT_DIALOG' })}
        >
          <Settings className="w-3 h-3 mr-2" />
          调整权重
        </Button>
      </Card>

      {/* 风险评估 */}
      <Card className="p-4">
        <h3 className="font-medium mb-4 flex items-center gap-2">
          <AlertTriangle className="w-4 h-4" />
          风险评估
        </h3>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">综合风险等级</span>
            <Badge
              variant={riskLevel.level === 'high' ? 'destructive' :
                      riskLevel.level === 'medium' ? 'default' : 'secondary'}
              className="capitalize"
            >
              {riskLevel.text}
            </Badge>
          </div>

          {state.analysisResults.length > 0 && (
            <>
              <div className="text-center py-2">
                <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {Math.round(
                    state.analysisResults.reduce((sum, r) => sum + r.overallScore, 0) /
                    state.analysisResults.length
                  )}分
                </div>
                <div className="text-xs text-muted-foreground">平均适宜性得分</div>
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted-foreground">优秀地块 (≥80分)</span>
                  <span className="font-medium">
                    {state.analysisResults.filter(r => r.overallScore >= 80).length} 个
                  </span>
                </div>
                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted-foreground">良好地块 (60-79分)</span>
                  <span className="font-medium">
                    {state.analysisResults.filter(r => r.overallScore >= 60 && r.overallScore < 80).length} 个
                  </span>
                </div>
                <div className="flex items-center justify-between text-xs">
                  <span className="text-muted-foreground">需改进 (&lt;60分)</span>
                  <span className="font-medium">
                    {state.analysisResults.filter(r => r.overallScore < 60).length} 个
                  </span>
                </div>
              </div>
            </>
          )}
        </div>
      </Card>

      {/* 快速操作 */}
      <Card className="p-4">
        <h3 className="font-medium mb-4 flex items-center gap-2">
          <TrendingUp className="w-4 h-4" />
          快速操作
        </h3>

        <div className="space-y-2">
          <Button
            variant="outline"
            size="sm"
            className="w-full"
            onClick={() => dispatch({ type: 'TOGGLE_FACTOR_DIALOG' })}
          >
            <Settings className="w-3 h-3 mr-2" />
            配置评价因子
          </Button>

          <Button
            variant="outline"
            size="sm"
            className="w-full"
            onClick={handleQuickAnalysis}
            disabled={state.landBlocks.length === 0}
          >
            <BarChart3 className="w-3 h-3 mr-2" />
            快速分析全部
          </Button>

          <Button
            variant="outline"
            size="sm"
            className="w-full"
            onClick={handleResetFilters}
            disabled={state.analysisResults.length === 0}
          >
            <Info className="w-3 h-3 mr-2" />
            重置筛选条件
          </Button>
        </div>
      </Card>

      {/* 分析建议 */}
      {state.analysisResults.length > 0 && (
        <Card className="p-4">
          <h3 className="font-medium mb-4 flex items-center gap-2">
            <CheckCircle className="w-4 h-4" />
            智能建议
          </h3>

          <div className="space-y-2 text-sm">
            <div className="p-2 bg-blue-50 dark:bg-blue-950 rounded text-blue-800 dark:text-blue-200">
              <p className="font-medium mb-1">优先推荐作物</p>
              <p className="text-xs">
                {(() => {
                  const cropCounts = state.analysisResults.flatMap(r =>
                    r.recommendedCrops.slice(0, 2).map(c => c.crop.name)
                  );
                  const topCrops = [...new Set(cropCounts)].slice(0, 3);
                  return topCrops.join('、');
                })()}
              </p>
            </div>

            <div className="p-2 bg-green-50 dark:bg-green-950 rounded text-green-800 dark:text-green-200">
              <p className="font-medium mb-1">最佳种植地块</p>
              <p className="text-xs">
                {state.analysisResults
                  .sort((a, b) => b.overallScore - a.overallScore)
                  .slice(0, 2)
                  .map(r => r.blockName)
                  .join('、')}
              </p>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}