'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 {
  Play,
  Pause,
  Square,
  RotateCcw,
  Clock,
  CheckCircle,
  XCircle,
  Loader2,
  Activity,
  Database,
  TrendingUp
} from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';
import BatchAnalysisManager from './batchAnalysisService';

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

export default function BatchAnalysisPanel({ state, dispatch }: BatchAnalysisPanelProps) {
  const manager = new BatchAnalysisManager(dispatch);

  const handleStartBatchAnalysis = async () => {
    if (state.selectedBlocks.length === 0) {
      alert('请先选择要分析的地块');
      return;
    }

    const selectedBlocksData = state.landBlocks.filter(block =>
      state.selectedBlocks.includes(block.id)
    );
    const enabledFactors = state.factors.filter(factor => factor.enabled);

    try {
      await manager.startBatchAnalysis(
        `批量分析_${new Date().toLocaleDateString('zh-CN')}`,
        selectedBlocksData,
        enabledFactors,
        state.weightConfig
      );
    } catch (error) {
      console.error('启动批量分析失败:', error);
      alert('启动批量分析失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  const handlePauseAnalysis = () => {
    manager.pauseAnalysis();
  };

  const handleResumeAnalysis = () => {
    manager.resumeAnalysis();
  };

  const handleCancelAnalysis = () => {
    if (confirm('确定要取消当前的分析任务吗？')) {
      manager.cancelAnalysis();
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-yellow-500" />;
      case 'running':
        return <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'paused':
        return <Pause className="w-4 h-4 text-orange-500" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-500" />;
      default:
        return <Activity className="w-4 h-4 text-gray-500" />;
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '等待开始';
      case 'running':
        return '正在分析';
      case 'paused':
        return '已暂停';
      case 'completed':
        return '已完成';
      case 'failed':
        return '分析失败';
      default:
        return '未知状态';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-50 border-yellow-200 dark:bg-yellow-950 dark:border-yellow-800';
      case 'running':
        return 'bg-blue-50 border-blue-200 dark:bg-blue-950 dark:border-blue-800';
      case 'paused':
        return 'bg-orange-50 border-orange-200 dark:bg-orange-950 dark:border-orange-800';
      case 'completed':
        return 'bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800';
      case 'failed':
        return 'bg-red-50 border-red-200 dark:bg-red-950 dark:border-red-800';
      default:
        return 'bg-gray-50 border-gray-200 dark:bg-gray-950 dark:border-gray-800';
    }
  };

  const currentTask = state.currentTask;

  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>
          <Badge variant="outline">
            已选择 {state.selectedBlocks.length} / {state.landBlocks.length} 个地块
          </Badge>
        </div>

        {/* 任务状态显示 */}
        {currentTask && (
          <div className={`p-4 rounded-lg border mb-6 ${getStatusColor(currentTask.status)}`}>
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                {getStatusIcon(currentTask.status)}
                <h4 className="font-medium">{currentTask.name}</h4>
              </div>
              <Badge variant="outline">
                {getStatusText(currentTask.status)}
              </Badge>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm mb-4">
              <div>
                <span className="text-muted-foreground">创建时间:</span>
                <div className="font-medium">{currentTask.createdAt}</div>
              </div>
              <div>
                <span className="text-muted-foreground">总地块:</span>
                <div className="font-medium">{currentTask.totalBlocks} 个</div>
              </div>
              <div>
                <span className="text-muted-foreground">已处理:</span>
                <div className="font-medium">{currentTask.processedBlocks} 个</div>
              </div>
              <div>
                <span className="text-muted-foreground">成功率:</span>
                <div className="font-medium text-green-600">
                  {currentTask.totalBlocks > 0
                    ? Math.round((currentTask.successCount / currentTask.processedBlocks) * 100)
                    : 0}%
                </div>
              </div>
            </div>

            {/* 进度条 */}
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>分析进度</span>
                <span>{currentTask.progress}%</span>
              </div>
              <Progress value={currentTask.progress} className="h-2" />
            </div>

            {/* 当前处理的地块 */}
            {currentTask.currentProcessingBlock && (
              <div className="mt-3 text-sm">
                <span className="text-muted-foreground">正在处理: </span>
                <span className="font-medium">{currentTask.currentProcessingBlock}</span>
              </div>
            )}

            {/* 错误信息 */}
            {currentTask.errorMessage && (
              <div className="mt-3 text-sm text-red-600">
                错误: {currentTask.errorMessage}
              </div>
            )}
          </div>
        )}

        {/* 控制按钮 */}
        <div className="flex items-center gap-3">
          {!state.isBatchAnalyzing && !currentTask && (
            <Button
              onClick={handleStartBatchAnalysis}
              disabled={state.selectedBlocks.length === 0}
              className="flex items-center gap-2"
            >
              <Play className="w-4 h-4" />
              开始批量分析
            </Button>
          )}

          {state.isBatchAnalyzing && currentTask && (
            <>
              <Button
                variant="outline"
                onClick={handlePauseAnalysis}
                className="flex items-center gap-2"
              >
                <Pause className="w-4 h-4" />
                暂停
              </Button>
              <Button
                variant="outline"
                onClick={handleCancelAnalysis}
                className="flex items-center gap-2"
              >
                <Square className="w-4 h-4" />
                取消
              </Button>
            </>
          )}

          {currentTask && currentTask.status === 'paused' && (
            <>
              <Button
                onClick={handleResumeAnalysis}
                className="flex items-center gap-2"
              >
                <Play className="w-4 h-4" />
                继续
              </Button>
              <Button
                variant="outline"
                onClick={handleCancelAnalysis}
                className="flex items-center gap-2"
              >
                <Square className="w-4 h-4" />
                取消
              </Button>
            </>
          )}

          {currentTask && currentTask.status === 'completed' && (
            <Button
              variant="outline"
              onClick={handleStartBatchAnalysis}
              className="flex items-center gap-2"
            >
              <RotateCcw className="w-4 h-4" />
              重新分析
            </Button>
          )}
        </div>
      </Card>

      {/* 分析配置信息 */}
      <Card className="p-6">
        <h4 className="font-medium mb-4 flex items-center gap-2">
          <TrendingUp className="w-4 h-4" />
          分析配置
        </h4>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <h5 className="text-sm font-medium mb-2">权重配置</h5>
            <div className="space-y-1 text-sm">
              <div className="flex justify-between">
                <span>土壤条件:</span>
                <span>{Math.round(state.weightConfig.soil * 100)}%</span>
              </div>
              <div className="flex justify-between">
                <span>气候条件:</span>
                <span>{Math.round(state.weightConfig.climate * 100)}%</span>
              </div>
              <div className="flex justify-between">
                <span>地形条件:</span>
                <span>{Math.round(state.weightConfig.topography * 100)}%</span>
              </div>
              <div className="flex justify-between">
                <span>基础设施:</span>
                <span>{Math.round(state.weightConfig.infrastructure * 100)}%</span>
              </div>
            </div>
          </div>

          <div>
            <h5 className="text-sm font-medium mb-2">评价因子</h5>
            <div className="space-y-1 text-sm">
              <div className="flex justify-between">
                <span>启用因子:</span>
                <span>{state.factors.filter(f => f.enabled).length} / {state.factors.length}</span>
              </div>
              <div className="flex justify-between">
                <span>土壤因子:</span>
                <span>{state.factors.filter(f => f.enabled && f.category === 'soil').length} 个</span>
              </div>
              <div className="flex justify-between">
                <span>气候因子:</span>
                <span>{state.factors.filter(f => f.enabled && f.category === 'climate').length} 个</span>
              </div>
              <div className="flex justify-between">
                <span>地形因子:</span>
                <span>{state.factors.filter(f => f.enabled && f.category === 'topography').length} 个</span>
              </div>
            </div>
          </div>
        </div>
      </Card>

      {/* 地块分析状态概览 */}
      {state.landBlocks.some(block => block.analysisStatus) && (
        <Card className="p-6">
          <h4 className="font-medium mb-4 flex items-center gap-2">
            <Activity className="w-4 h-4" />
            地块分析状态
          </h4>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="text-center">
              <div className="text-2xl font-bold text-blue-600">
                {state.landBlocks.filter(b => b.analysisStatus === 'pending').length}
              </div>
              <div className="text-sm text-muted-foreground">等待分析</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-orange-600">
                {state.landBlocks.filter(b => b.analysisStatus === 'analyzing').length}
              </div>
              <div className="text-sm text-muted-foreground">正在分析</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-green-600">
                {state.landBlocks.filter(b => b.analysisStatus === 'completed').length}
              </div>
              <div className="text-sm text-muted-foreground">分析完成</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-red-600">
                {state.landBlocks.filter(b => b.analysisStatus === 'failed').length}
              </div>
              <div className="text-sm text-muted-foreground">分析失败</div>
            </div>
          </div>
        </Card>
      )}

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <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>: 选择多个地块，系统将自动循环调用空间分析服务</li>
              <li>• <strong>因子读取</strong>: 自动读取土壤、气候、地形、基础设施等各项因子数据</li>
              <li>• <strong>加权计算</strong>: 根据配置的权重和因子进行综合评分计算</li>
              <li>• <strong>适宜性指数</strong>: 生成0-100的适宜性指数并自动更新到数据库</li>
              <li>• <strong>进度监控</strong>: 实时显示分析进度，支持暂停、继续、取消操作</li>
              <li>• <strong>结果保存</strong>: 分析完成后自动保存结果，可查看详细报告</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}