'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 { toast } from 'sonner';
import {
  Database,
  CheckCircle2,
  AlertTriangle,
  Target,
  Droplet,
  Cloud,
  Sun,
  ThermometerSun,
  Zap,
  RefreshCw,
  Play,
  Pause,
  Square
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction, AnalysisResult } from './spatialAnalysisReducer';
import { useState, useEffect } from 'react';
import BatchAnalysisManager from './batchAnalysisService';

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

export default function BatchEvaluationPanel({ state, dispatch }: BatchEvaluationPanelProps) {
  const [batchManager, setBatchManager] = useState<BatchAnalysisManager | null>(null);

  useEffect(() => {
    setBatchManager(new BatchAnalysisManager(dispatch));
  }, [dispatch]);

  const totalWeight = Math.round(
    (state.weightConfig.soil + state.weightConfig.climate +
     state.weightConfig.topography + state.weightConfig.infrastructure) * 100
  );

  const handleStartBatchAnalysis = async () => {
    if (totalWeight !== 100) {
      toast.error(`权重总和必须为100%才能进行批量分析（当前：${totalWeight}%）`);
      return;
    }

    const enabledFactors = state.factors.filter(f => f.enabled);
    if (enabledFactors.length < 3) {
      toast.error('至少需要启用3个评价因子才能进行批量分析');
      return;
    }

    if (!batchManager) {
      toast.error('批量分析服务未初始化');
      return;
    }

    try {
      // 创建批量分析任务
      const taskName = `地块适宜性批量分析_${new Date().toLocaleString('zh-CN')}`;

      // 固定分析68个地块
      const totalFields = 68;
      const blockIds = Array.from({ length: totalFields }, (_, i) => `field-${i + 1}`);

      // 开始批量分析
      await batchManager.startBatchAnalysis(taskName, enabledFactors, state.weightConfig);

      toast.success('批量分析任务已启动，正在处理地块数据...');

    } catch (error) {
      console.error('启动批量分析失败:', error);
      toast.error('启动批量分析失败，请重试');
    }
  };

  const handlePauseAnalysis = () => {
    if (batchManager && state.currentTask) {
      batchManager.pauseAnalysis();
      toast.info('批量分析已暂停');
    }
  };

  const handleResumeAnalysis = () => {
    if (batchManager && state.currentTask) {
      batchManager.resumeAnalysis();
      toast.info('批量分析已恢复');
    }
  };

  const handleCancelAnalysis = () => {
    if (batchManager && state.currentTask) {
      batchManager.cancelAnalysis();
      toast.info('批量分析已取消');
    }
  };

  const currentTask = state.currentTask;

  // 计算统计结果
  const resultsForStats = state.analysisResults;
  const highSuitability = resultsForStats.filter(r => r.overallScore >= 80).length;
  const mediumSuitability = resultsForStats.filter(r => r.overallScore >= 60 && r.overallScore < 80).length;
  const lowSuitability = resultsForStats.filter(r => r.overallScore < 60).length;

  return (
    <div className="space-y-6">
      {/* 主要批量分析控制面板 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-lg font-medium flex items-center gap-2">
            <Database className="w-5 h-5" />
            批量评价地块
          </h3>
          <div className="flex items-center gap-2">
            <Badge variant="outline">
              68 个地块
            </Badge>
            {currentTask && (
              <Badge
                variant={
                  currentTask.status === 'completed' ? 'default' :
                  currentTask.status === 'running' ? 'secondary' :
                  currentTask.status === 'failed' ? 'destructive' : 'outline'
                }
              >
                {currentTask.status === 'pending' && '等待中'}
                {currentTask.status === 'running' && '分析中'}
                {currentTask.status === 'completed' && '已完成'}
                {currentTask.status === 'failed' && '失败'}
                {currentTask.status === 'paused' && '已暂停'}
                {currentTask.status === 'cancelled' && '已取消'}
              </Badge>
            )}
          </div>
        </div>

        {/* 控制按钮区域 */}
        <div className="flex items-center gap-3 mb-6">
          {!currentTask || currentTask.status === 'completed' || currentTask.status === 'failed' || currentTask.status === 'cancelled' ? (
            <Button
              size="lg"
              className="bg-green-600 hover:bg-green-700"
              onClick={handleStartBatchAnalysis}
              disabled={state.isBatchAnalyzing || totalWeight !== 100}
            >
              <Play className="w-5 h-5 mr-2" />
              开始批量分析
            </Button>
          ) : (
            <>
              {currentTask.status === 'running' && (
                <Button
                  size="lg"
                  variant="outline"
                  onClick={handlePauseAnalysis}
                >
                  <Pause className="w-5 h-5 mr-2" />
                  暂停分析
                </Button>
              )}
              {currentTask.status === 'paused' && (
                <Button
                  size="lg"
                  className="bg-blue-600 hover:bg-blue-700"
                  onClick={handleResumeAnalysis}
                >
                  <Play className="w-5 h-5 mr-2" />
                  恢复分析
                </Button>
              )}
              <Button
                size="lg"
                variant="destructive"
                onClick={handleCancelAnalysis}
              >
                <Square className="w-5 h-5 mr-2" />
                取消分析
              </Button>
            </>
          )}
        </div>

        {/* 权重和因子验证警告 */}
        {totalWeight !== 100 && (
          <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <p className="text-sm text-yellow-800">
              ⚠️ 权重总和必须为100%才能进行批量分析（当前：{totalWeight}%）
            </p>
          </div>
        )}

        {state.factors.filter(f => f.enabled).length < 3 && (
          <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <p className="text-sm text-yellow-800">
              ⚠️ 至少需要启用3个评价因子才能进行批量分析（当前：{state.factors.filter(f => f.enabled).length}个）
            </p>
          </div>
        )}

        {/* 分析进行中的状态显示 */}
        {currentTask && (currentTask.status === 'running' || currentTask.status === 'paused') && (
          <div className="space-y-4">
            <div className="flex items-center justify-between text-sm">
              <span className="text-muted-foreground">分析进度</span>
              <span className="font-medium">{currentTask.progress}%</span>
            </div>
            <Progress value={currentTask.progress} className="h-3" />

            <div className="grid grid-cols-2 gap-3 text-sm">
              <div className="p-3 bg-blue-50 rounded-lg">
                <p className="text-xs text-muted-foreground">当前处理</p>
                <p className="mt-1 text-blue-900">{currentTask.currentProcessingBlock || '准备中...'}</p>
              </div>
              <div className="p-3 bg-blue-50 rounded-lg">
                <p className="text-xs text-muted-foreground">处理进度</p>
                <p className="mt-1 text-blue-900">
                  {currentTask.processedBlocks} / {currentTask.totalBlocks} 地块
                </p>
              </div>
              <div className="p-3 bg-green-50 rounded-lg">
                <p className="text-xs text-muted-foreground">成功数量</p>
                <p className="mt-1 text-green-900">{currentTask.successCount}</p>
              </div>
              <div className="p-3 bg-red-50 rounded-lg">
                <p className="text-xs text-muted-foreground">失败数量</p>
                <p className="mt-1 text-red-900">{currentTask.failedCount}</p>
              </div>
            </div>

            <div className="text-xs text-muted-foreground space-y-1">
              <p>✓ 正在从空间分析服务读取因子数据...</p>
              <p>✓ 正在计算各因子得分（pH、有机质、土层厚度、全氮、全磷、全钾、排水性）...</p>
              <p>✓ 正在进行加权汇总计算...</p>
              <p>✓ 正在生成适宜性指数并更新到数据库...</p>
            </div>

            {/* 任务状态信息 */}
            <div className="p-3 bg-gray-50 rounded-lg">
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div>
                  <span className="text-muted-foreground">任务名称：</span>
                  <span className="font-medium">{currentTask.name}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">创建时间：</span>
                  <span className="font-medium">{currentTask.createdAt}</span>
                </div>
                {currentTask.startedAt && (
                  <div>
                    <span className="text-muted-foreground">开始时间：</span>
                    <span className="font-medium">{currentTask.startedAt}</span>
                  </div>
                )}
                <div>
                  <span className="text-muted-foreground">启用因子：</span>
                  <span className="font-medium">{state.factors.filter(f => f.enabled).length}个</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 分析完成状态 */}
        {currentTask && currentTask.status === 'completed' && (
          <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
            <p className="text-sm text-green-800">
              ✓ 批量分析已完成！已为 {currentTask.totalBlocks} 个地块生成适宜性评价结果并更新到数据库
            </p>
            <div className="mt-2 text-xs text-green-700">
              <div>完成时间：{currentTask.completedAt}</div>
              <div>成功分析：{currentTask.successCount} 个地块</div>
              {currentTask.failedCount > 0 && (
                <div>分析失败：{currentTask.failedCount} 个地块</div>
              )}
            </div>
          </div>
        )}

        {/* 分析失败状态 */}
        {currentTask && currentTask.status === 'failed' && (
          <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
            <p className="text-sm text-red-800">
              ✗ 批量分析失败：{currentTask.errorMessage || '未知错误'}
            </p>
            <div className="mt-2 text-xs text-red-700">
              <div>已处理：{currentTask.processedBlocks} 个地块</div>
              <div>成功：{currentTask.successCount} 个地块</div>
            </div>
          </div>
        )}
      </Card>

      {/* 批量分析结果统计 */}
      {resultsForStats.length > 0 && (
        <div className="grid grid-cols-3 gap-4">
          <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">高度适宜</p>
                <p className="mt-2 text-3xl text-green-600">{highSuitability}</p>
                <p className="text-xs text-muted-foreground mt-1">
                  地块数量 ({Math.round((highSuitability / resultsForStats.length) * 100)}%)
                </p>
              </div>
              <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
            </div>
          </Card>

          <Card className="p-6 bg-gradient-to-br from-yellow-50 to-yellow-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">一般适宜</p>
                <p className="mt-2 text-3xl text-yellow-600">{mediumSuitability}</p>
                <p className="text-xs text-muted-foreground mt-1">
                  地块数量 ({Math.round((mediumSuitability / resultsForStats.length) * 100)}%)
                </p>
              </div>
              <AlertTriangle className="w-12 h-12 text-yellow-600 opacity-50" />
            </div>
          </Card>

          <Card className="p-6 bg-gradient-to-br from-red-50 to-red-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">不适宜</p>
                <p className="mt-2 text-3xl text-red-600">{lowSuitability}</p>
                <p className="text-xs text-muted-foreground mt-1">
                  地块数量 ({Math.round((lowSuitability / resultsForStats.length) * 100)}%)
                </p>
              </div>
              <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
            </div>
          </Card>
        </div>
      )}

      {/* 分析说明卡片 */}
      <Card className="p-6">
        <h4 className="font-medium mb-4 flex items-center gap-2">
          <Zap className="w-4 h-4 text-yellow-500" />
          空间分析服务说明
        </h4>

        <div className="space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="text-center">
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-2">
                <Target className="w-6 h-6 text-blue-600" />
              </div>
              <h5 className="font-medium text-sm">土壤因子</h5>
              <p className="text-xs text-muted-foreground mt-1">
                pH值、有机质、土层厚度、全氮、全磷、全钾、排水性
              </p>
            </div>

            <div className="text-center">
              <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-2">
                <Droplet className="w-6 h-6 text-green-600" />
              </div>
              <h5 className="font-medium text-sm">水分因子</h5>
              <p className="text-xs text-muted-foreground mt-1">
                地下水位、灌溉保证率、排水能力、土壤含水量
              </p>
            </div>

            <div className="text-center">
              <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-2">
                <Sun className="w-6 h-6 text-yellow-600" />
              </div>
              <h5 className="font-medium text-sm">气候因子</h5>
              <p className="text-xs text-muted-foreground mt-1">
                年均温度、年降雨量、日照时数、无霜期、积温
              </p>
            </div>

            <div className="text-center">
              <div className="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-2">
                <ThermometerSun className="w-6 h-6 text-purple-600" />
              </div>
              <h5 className="font-medium text-sm">地形因子</h5>
              <p className="text-xs text-muted-foreground mt-1">
                海拔高度、坡度、坡向、地貌类型、侵蚀程度
              </p>
            </div>
          </div>

          <div className="p-4 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-lg">
            <div className="flex gap-2">
              <Database 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>• <strong>数据读取</strong>: 自动从空间分析服务读取68个地块的多维度因子数据</li>
                  <li>• <strong>因子评分</strong>: 根据最优值范围计算每个因子的得分（0-100分）</li>
                  <li>• <strong>加权汇总</strong>: 按照配置的权重计算综合适宜性指数</li>
                  <li>• <strong>等级划分</strong>: 根据综合得分确定适宜性等级（高度适宜/一般适宜/不适宜）</li>
                  <li>• <strong>数据库更新</strong>: 将评价结果和适宜性指数自动更新到数据库</li>
                  <li>• <strong>结果统计</strong>: 生成详细的统计分析和可视化报告</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}