/**
 * filekorolheader: 智能调度管理页面 - AI模型任务调度与监控平台
 * 功能：任务队列管理、优先级调度、异常重试机制、执行记录追踪、手动触发任务
 * 路径：/ai-crop-model/model-application/scheduling
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useReducer状态管理，shadcn语义化样式，支持暗色主题
 */

'use client';

import { useReducer, useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import {
  Timer,
  Plus,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  PauseCircle,
  Eye,
  Clock,
  Zap,
  Activity,
  Calendar,
  Settings,
  RefreshCw,
  Rocket,
  FileText,
} from 'lucide-react';
import { toast } from 'sonner';

// 类型定义
type TaskStatus = '等待中' | '运行中' | '已完成' | '失败' | '已取消';
type TriggerType = '定时触发' | '周期触发' | '事件触发' | '手动触发';
type Priority = '高' | '中' | '低';

interface ScheduleTask {
  id: string;
  taskNo: string;
  applicationName: string;
  triggerType: TriggerType;
  priority: Priority;
  status: TaskStatus;
  scheduledTime: string;
  actualStartTime?: string;
  actualEndTime?: string;
  executionTime?: number;
  retryCount: number;
  maxRetry: number;
  result?: string;
  errorMessage?: string;
  createdAt: string;
  updatedAt: string;
}

interface TaskQueue {
  waiting: number;
  running: number;
  completed: number;
  failed: number;
}

interface SchedulingState {
  scheduleTasks: ScheduleTask[];
  taskQueue: TaskQueue;
  selectedTask: ScheduleTask | null;
  showTaskDialog: boolean;
  showCreateDialog: boolean;
  loading: boolean;
}

type SchedulingAction =
  | { type: 'SET_SCHEDULE_TASKS'; payload: ScheduleTask[] }
  | { type: 'SET_TASK_QUEUE'; payload: TaskQueue }
  | { type: 'SET_SELECTED_TASK'; payload: ScheduleTask | null }
  | { type: 'TOGGLE_TASK_DIALOG' }
  | { type: 'TOGGLE_CREATE_DIALOG' }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'UPDATE_TASK_STATUS'; payload: { id: string; status: TaskStatus } }
  | { type: 'ADD_SCHEDULE_TASK'; payload: ScheduleTask };

// 初始状态
const initialState: SchedulingState = {
  scheduleTasks: [
    {
      id: 'task-1',
      taskNo: 'TASK-20240315-001',
      applicationName: '番茄生长预测模型',
      triggerType: '定时触发',
      priority: '高',
      status: '运行中',
      scheduledTime: '2024-03-15 08:00:00',
      actualStartTime: '2024-03-15 08:00:15',
      executionTime: 125,
      retryCount: 0,
      maxRetry: 3,
      result: '预测完成，预计生长周期为85天',
      createdAt: '2024-03-15 07:55:00',
      updatedAt: '2024-03-15 08:02:20',
    },
    {
      id: 'task-2',
      taskNo: 'TASK-20240315-002',
      applicationName: '病虫害智能识别',
      triggerType: '周期触发',
      priority: '中',
      status: '等待中',
      scheduledTime: '2024-03-15 09:00:00',
      retryCount: 0,
      maxRetry: 3,
      createdAt: '2024-03-15 08:30:00',
      updatedAt: '2024-03-15 08:30:00',
    },
    {
      id: 'task-3',
      taskNo: 'TASK-20240315-003',
      applicationName: '产量预估分析',
      triggerType: '事件触发',
      priority: '低',
      status: '已完成',
      scheduledTime: '2024-03-15 07:30:00',
      actualStartTime: '2024-03-15 07:30:05',
      actualEndTime: '2024-03-15 07:31:34',
      executionTime: 89,
      retryCount: 0,
      maxRetry: 3,
      result: '预估产量为12500公斤，置信度92%',
      createdAt: '2024-03-15 07:25:00',
      updatedAt: '2024-03-15 07:31:34',
    },
    {
      id: 'task-4',
      taskNo: 'TASK-20240315-004',
      applicationName: '土壤养分分析',
      triggerType: '手动触发',
      priority: '中',
      status: '失败',
      scheduledTime: '2024-03-15 06:00:00',
      actualStartTime: '2024-03-15 06:00:12',
      actualEndTime: '2024-03-15 06:00:57',
      executionTime: 45,
      retryCount: 2,
      maxRetry: 3,
      errorMessage: '数据源连接超时，请检查传感器状态',
      createdAt: '2024-03-15 05:55:00',
      updatedAt: '2024-03-15 06:02:48',
    },
  ],
  taskQueue: {
    waiting: 8,
    running: 3,
    completed: 156,
    failed: 2,
  },
  selectedTask: null,
  showTaskDialog: false,
  showCreateDialog: false,
  loading: false,
};

// Reducer
function schedulingReducer(state: SchedulingState, action: SchedulingAction): SchedulingState {
  switch (action.type) {
    case 'SET_SCHEDULE_TASKS':
      return { ...state, scheduleTasks: action.payload };
    case 'SET_TASK_QUEUE':
      return { ...state, taskQueue: action.payload };
    case 'SET_SELECTED_TASK':
      return { ...state, selectedTask: action.payload };
    case 'TOGGLE_TASK_DIALOG':
      return { ...state, showTaskDialog: !state.showTaskDialog };
    case 'TOGGLE_CREATE_DIALOG':
      return { ...state, showCreateDialog: !state.showCreateDialog };
    case 'SET_LOADING':
      return { ...state, loading: action.payload };
    case 'UPDATE_TASK_STATUS':
      return {
        ...state,
        scheduleTasks: state.scheduleTasks.map(task =>
          task.id === action.payload.id
            ? { ...task, status: action.payload.status, updatedAt: new Date().toISOString() }
            : task
        ),
      };
    case 'ADD_SCHEDULE_TASK':
      return {
        ...state,
        scheduleTasks: [action.payload, ...state.scheduleTasks],
      };
    default:
      return state;
  }
}

export default function SchedulingPage() {
  const [state, dispatch] = useReducer(schedulingReducer, initialState);

  useEffect(() => {
    dispatch({ type: 'SET_LOADING', payload: true });
    // 模拟数据加载
    setTimeout(() => {
      dispatch({ type: 'SET_LOADING', payload: false });
    }, 1000);
  }, []);

  // 工具函数
  const getStatusIcon = (status: TaskStatus) => {
    switch (status) {
      case '等待中': return <Clock className="w-4 h-4 text-yellow-500" />;
      case '运行中': return <Activity className="w-4 h-4 text-blue-500" />;
      case '已完成': return <CheckCircle className="w-4 h-4 text-green-500" />;
      case '失败': return <XCircle className="w-4 h-4 text-red-500" />;
      case '已取消': return <PauseCircle className="w-4 h-4 text-gray-500" />;
      default: return <AlertCircle className="w-4 h-4 text-gray-500" />;
    }
  };

  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '等待中': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case '运行中': return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
      case '已完成': return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case '失败': return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      case '已取消': return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getPriorityColor = (priority: Priority) => {
    switch (priority) {
      case '高': return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      case '中': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case '低': return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  // 事件处理函数
  const handleCreateScheduleTask = () => {
    dispatch({ type: 'TOGGLE_CREATE_DIALOG' });
  };

  const handleManualTriggerTask = (task: ScheduleTask) => {
    toast.success(`任务 ${task.taskNo} 已手动触发执行`);
    dispatch({ type: 'UPDATE_TASK_STATUS', payload: { id: task.id, status: '运行中' } });
  };

  const handleViewTaskDetail = (task: ScheduleTask) => {
    dispatch({ type: 'SET_SELECTED_TASK', payload: task });
    dispatch({ type: 'TOGGLE_TASK_DIALOG' });
  };

  const handleRetryTask = (task: ScheduleTask) => {
    toast.success(`任务 ${task.taskNo} 已重新加入队列`);
    dispatch({ type: 'UPDATE_TASK_STATUS', payload: { id: task.id, status: '等待中' } });
  };

  const handleCancelTask = (task: ScheduleTask) => {
    toast.success(`任务 ${task.taskNo} 已取消`);
    dispatch({ type: 'UPDATE_TASK_STATUS', payload: { id: task.id, status: '已取消' } });
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h2 className="text-3xl font-bold tracking-tight">智能调度管理</h2>
        <p className="text-muted-foreground mt-1">
          AI模型任务调度与监控平台，智能化管理任务执行队列
        </p>
      </div>

      {/* 功能说明卡片 */}
      <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200 dark:from-purple-950 dark:to-pink-950 dark:border-purple-800">
        <div className="flex items-start gap-2">
          <Timer className="w-5 h-5 text-purple-600 dark:text-purple-400 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-purple-900 dark:text-purple-100">
            <p className="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>: 完整记录任务生命周期全过程</li>
              <li>• <strong>7×24运行</strong>: 无人值守稳定运行，智能化调度</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 任务队列状态 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4 bg-yellow-50 dark:bg-yellow-950">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-yellow-100 dark:bg-yellow-900 rounded-full flex items-center justify-center">
              <Clock className="w-5 h-5 text-yellow-600 dark:text-yellow-400" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">等待中</p>
              <p className="text-2xl text-yellow-600 dark:text-yellow-400">{state.taskQueue.waiting}</p>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-blue-50 dark:bg-blue-950">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
              <Activity className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">运行中</p>
              <p className="text-2xl text-blue-600 dark:text-blue-400">{state.taskQueue.running}</p>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-green-50 dark:bg-green-950">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
              <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">已完成</p>
              <p className="text-2xl text-green-600 dark:text-green-400">{state.taskQueue.completed}</p>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-red-50 dark:bg-red-950">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center">
              <XCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
            </div>
            <div>
              <p className="text-xs text-muted-foreground">失败</p>
              <p className="text-2xl text-red-600 dark:text-red-400">{state.taskQueue.failed}</p>
            </div>
          </div>
        </Card>
      </div>

      {/* 调度任务列表 */}
      <div>
        <div className="mb-4 flex items-center justify-between">
          <h3 className="flex items-center gap-2 text-lg font-semibold">
            <Timer className="w-5 h-5 text-purple-600 dark:text-purple-400" />
            调度任务列表
          </h3>
          <Button
            className="bg-purple-600 hover:bg-purple-700 dark:bg-purple-700 dark:hover:bg-purple-600"
            onClick={handleCreateScheduleTask}
          >
            <Plus className="w-4 h-4 mr-2" />
            新增调度任务
          </Button>
        </div>

        <div className="grid grid-cols-1 gap-4">
          {state.scheduleTasks.map((task) => (
            <Card key={task.id} className="p-6">
              <div className="flex items-start justify-between">
                <div className="flex-1 space-y-3">
                  <div className="flex items-center gap-4">
                    <span className="font-mono text-sm text-muted-foreground">{task.taskNo}</span>
                    <h4 className="font-medium">{task.applicationName}</h4>
                    <Badge variant="outline">{task.triggerType}</Badge>
                    <Badge className={getPriorityColor(task.priority)}>{task.priority}</Badge>
                  </div>
                  <div className="grid grid-cols-4 gap-4 text-sm">
                    <div>
                      <p className="text-xs text-muted-foreground">计划时间</p>
                      <p>{task.scheduledTime}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">实际开始</p>
                      <p>{task.actualStartTime || '-'}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">执行耗时</p>
                      <p>{task.executionTime ? `${task.executionTime}秒` : '-'}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">重试次数</p>
                      <p>{task.retryCount}/{task.maxRetry}</p>
                    </div>
                  </div>
                  {task.result && (
                    <div className="text-sm">
                      <p className="text-xs text-muted-foreground">执行结果</p>
                      <p className="text-green-600 dark:text-green-400">{task.result}</p>
                    </div>
                  )}
                  {task.errorMessage && (
                    <div className="text-sm">
                      <p className="text-xs text-muted-foreground">错误信息</p>
                      <p className="text-red-600 dark:text-red-400">{task.errorMessage}</p>
                    </div>
                  )}
                </div>
                <div className="flex flex-col items-end gap-3">
                  <div className="flex items-center gap-2">
                    {getStatusIcon(task.status)}
                    <Badge className={getStatusColor(task.status)}>{task.status}</Badge>
                  </div>
                  <div className="flex gap-2">
                    {task.status === '等待中' && (
                      <Button
                        size="sm"
                        className="bg-green-600 hover:bg-green-700 dark:bg-green-700 dark:hover:bg-green-600"
                        onClick={() => handleManualTriggerTask(task)}
                      >
                        <Zap className="w-3 h-3 mr-1" />
                        手动执行
                      </Button>
                    )}
                    {task.status === '失败' && task.retryCount < task.maxRetry && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleRetryTask(task)}
                      >
                        <RefreshCw className="w-3 h-3 mr-1" />
                        重试
                      </Button>
                    )}
                    {(task.status === '等待中' || task.status === '运行中') && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleCancelTask(task)}
                      >
                        <PauseCircle className="w-3 h-3 mr-1" />
                        取消
                      </Button>
                    )}
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleViewTaskDetail(task)}
                    >
                      <Eye className="w-3 h-3 mr-1" />
                      详情
                    </Button>
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* 任务详情对话框 */}
      <TaskDetailDialog
        open={state.showTaskDialog}
        onOpenChange={() => dispatch({ type: 'TOGGLE_TASK_DIALOG' })}
        task={state.selectedTask}
        getStatusIcon={getStatusIcon}
        getStatusColor={getStatusColor}
        getPriorityColor={getPriorityColor}
      />

      {/* 新增调度任务对话框 */}
      <CreateScheduleTaskDialog
        open={state.showCreateDialog}
        onOpenChange={() => dispatch({ type: 'TOGGLE_CREATE_DIALOG' })}
        onTaskCreated={(task) => {
          dispatch({ type: 'ADD_SCHEDULE_TASK', payload: task });
          toast.success('调度任务创建成功');
        }}
      />
    </div>
  );
}

// 任务详情对话框组件
function TaskDetailDialog({
  open,
  onOpenChange,
  task,
  getStatusIcon,
  getStatusColor,
  getPriorityColor
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  task: ScheduleTask | null;
  getStatusIcon: (status: TaskStatus) => React.ReactNode;
  getStatusColor: (status: TaskStatus) => string;
  getPriorityColor: (priority: Priority) => string;
}) {
  if (!task) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>任务详情</DialogTitle>
          <DialogDescription>
            任务编号: {task.taskNo}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>应用名称</Label>
              <div className="mt-1 p-2 bg-muted rounded text-sm">{task.applicationName}</div>
            </div>
            <div>
              <Label>触发方式</Label>
              <div className="mt-1">
                <Badge variant="outline">{task.triggerType}</Badge>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>优先级</Label>
              <div className="mt-1">
                <Badge className={getPriorityColor(task.priority)}>{task.priority}</Badge>
              </div>
            </div>
            <div>
              <Label>任务状态</Label>
              <div className="mt-1 flex items-center gap-2">
                {getStatusIcon(task.status)}
                <Badge className={getStatusColor(task.status)}>{task.status}</Badge>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>计划执行时间</Label>
              <div className="mt-1 p-2 bg-muted rounded text-sm">{task.scheduledTime}</div>
            </div>
            <div>
              <Label>实际开始时间</Label>
              <div className="mt-1 p-2 bg-muted rounded text-sm">{task.actualStartTime || '-'}</div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>实际结束时间</Label>
              <div className="mt-1 p-2 bg-muted rounded text-sm">{task.actualEndTime || '-'}</div>
            </div>
            <div>
              <Label>执行耗时</Label>
              <div className="mt-1 p-2 bg-muted rounded text-sm">{task.executionTime ? `${task.executionTime}秒` : '-'}</div>
            </div>
          </div>

          <div>
            <Label>重试信息</Label>
            <div className="mt-1 p-2 bg-muted rounded text-sm">
              已重试 {task.retryCount} 次，最大重试 {task.maxRetry} 次
            </div>
          </div>

          {/* 执行状态监控 */}
          <Card className="p-4 bg-blue-50 border-blue-200 dark:bg-blue-950 dark:border-blue-800">
            <h4 className="mb-3 flex items-center gap-2">
              <Activity className="w-4 h-4 text-blue-600 dark:text-blue-400" />
              执行状态监控
            </h4>

            {/* 状态时间轴 */}
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                  task.status !== '等待中' ? 'bg-green-500' : 'bg-gray-300'
                }`}>
                  {task.status !== '等待中' ? (
                    <CheckCircle className="w-4 h-4 text-white" />
                  ) : (
                    <Clock className="w-4 h-4 text-gray-600" />
                  )}
                </div>
                <div className="flex-1">
                  <p className="text-sm">任务创建</p>
                  <p className="text-xs text-muted-foreground">{task.scheduledTime}</p>
                </div>
              </div>
              {task.actualStartTime && (
                <div className="flex items-start gap-3">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                    task.status === '已完成' || task.status === '失败' ? 'bg-green-500' : 'bg-blue-500'
                  }`}>
                    {task.status === '运行中' ? (
                      <Activity className="w-4 h-4 text-white animate-pulse" />
                    ) : (
                      <PlayCircle className="w-4 h-4 text-white" />
                    )}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm">
                      {task.status === '运行中' ? '正在执行' : task.status === '已完成' ? '执行完成' : task.status === '失败' ? '执行失败' : '执行开始'}
                    </p>
                    <p className="text-xs text-muted-foreground">{task.actualStartTime}</p>
                  </div>
                </div>
              )}
              {(task.actualEndTime || (task.status === '已完成' || task.status === '失败')) && (
                <div className="flex items-start gap-3">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                    task.status === '已完成' ? 'bg-green-500' : task.status === '失败' ? 'bg-red-500' : 'bg-gray-300'
                  }`}>
                    {task.status === '已完成' ? (
                      <CheckCircle className="w-4 h-4 text-white" />
                    ) : task.status === '失败' ? (
                      <XCircle className="w-4 h-4 text-white" />
                    ) : (
                      <PauseCircle className="w-4 h-4 text-gray-600" />
                    )}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm">
                      {task.status === '已完成' ? '任务完成' : task.status === '失败' ? '任务失败' : '任务结束'}
                    </p>
                    <p className="text-xs text-muted-foreground">{task.actualEndTime || '执行中...'}</p>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {task.result && (
            <div>
              <Label>执行结果</Label>
              <div className="mt-1 p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded text-sm text-green-800 dark:text-green-200">
                {task.result}
              </div>
            </div>
          )}

          {task.errorMessage && (
            <div>
              <Label>错误信息</Label>
              <div className="mt-1 p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded text-sm text-red-800 dark:text-red-200">
                {task.errorMessage}
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            关闭
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// 新增调度任务对话框组件
function CreateScheduleTaskDialog({
  open,
  onOpenChange,
  onTaskCreated
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onTaskCreated: (task: ScheduleTask) => void;
}) {
  const [newTaskStep, setNewTaskStep] = useState(1);
  const [newTaskData, setNewTaskData] = useState({
    name: '',
    applicationName: '',
    inputSources: {} as Record<string, string>,
    priority: '' as Priority | '',
    timeStrategy: '' as '定时' | '周期' | '每天' | '',
    scheduledTime: '',
    cronExpression: '',
    enableManualTrigger: false,
  });

  // 应用数据
  const [applications] = useState([
    {
      id: 'app-1',
      name: '智能灌溉策略生成',
      type: '智能灌溉',
      description: '基于土壤湿度、天气预报和作物需水模型，自动生成最优灌溉方案',
      modelName: '灌溉优化模型',
      modelVersion: 'v2.1.0',
      inputConfig: {
        fields: ['土壤湿度', '温度', '降水预报', '作物类型', '生长阶段'],
      },
      outputConfig: {
        format: '折线图',
      },
      status: '运行中',
    },
    {
      id: 'app-2',
      name: '病虫害智能预警',
      type: '病虫害预警',
      description: '实时分析作物图像和环境数据，及时发现病虫害并推送预警',
      modelName: '病虫害识别模型',
      modelVersion: 'v1.8.0',
      inputConfig: {
        fields: ['作物图像', '温湿度', '历史病害记录'],
      },
      outputConfig: {
        format: '表格',
      },
      status: '运行中',
    },
    {
      id: 'app-3',
      name: '精准施肥智能推荐',
      type: '施肥推荐',
      description: '根据土壤养分检测结果和作物生长需求，生成精准施肥方案',
      modelName: '营养需求模型',
      modelVersion: 'v1.5.0',
      inputConfig: {
        fields: ['N含量', 'P含量', 'K含量', '作物品种', 'pH值'],
      },
      outputConfig: {
        format: '饼状图',
      },
      status: '运行中',
    },
  ]);

  // 数据源选项
  const [dataSourceOptions] = useState([
    '传感器实时数据',
    '数据库查询',
    '手动输入',
    '第三方API',
    '历史数据',
    '配置文件',
    'IoT设备',
    '气象站',
  ]);

  // 物联设备选项
  const [iotDeviceOptions] = useState([
    '土壤传感器01 (SN:SS-001)',
    '温湿度传感器02 (SN:TH-002)',
    '光照传感器03 (SN:LS-003)',
    'pH传感器04 (SN:PH-004)',
    '水肥一体机05 (SN:WF-005)',
    '气象站06 (SN:WS-006)',
    '作物图像采集器07 (SN:IC-007)',
    '水泵控制器08 (SN:PC-008)',
  ]);

  const selectedApplication = applications.find(app => app.name === newTaskData.applicationName);

  const handleNewTaskNextStep = () => {
    if (newTaskStep === 1) {
      if (!newTaskData.name || !newTaskData.applicationName) {
        toast.error('请填写任务名称并选择应用');
        return;
      }
    } else if (newTaskStep === 2) {
      // 验证输入源配置
      if (selectedApplication) {
        const fields = selectedApplication.inputConfig.fields || [];
        const emptyFields = fields.filter(field => !newTaskData.inputSources[field]);
        if (emptyFields.length > 0) {
          toast.error(`请为所有输入参数配置数据源：${emptyFields.join('、')}`);
          return;
        }
      }
    } else if (newTaskStep === 3) {
      if (!newTaskData.priority || !newTaskData.timeStrategy) {
        toast.error('请选择优先级和时间策略');
        return;
      }
      if (newTaskData.timeStrategy === '定时' && !newTaskData.scheduledTime) {
        toast.error('请设置定时执行时间');
        return;
      }
      if (newTaskData.timeStrategy === '周期' && !newTaskData.cronExpression) {
        toast.error('请设置周期表达式');
        return;
      }
    }
    setNewTaskStep(newTaskStep + 1);
  };

  const handleNewTaskPrevStep = () => {
    setNewTaskStep(newTaskStep - 1);
  };

  const handleCreateTask = () => {
    const newTask: ScheduleTask = {
      id: `task-${Date.now()}`,
      taskNo: `TASK-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${Math.random().toString(36).substr(2, 3).toUpperCase()}`,
      applicationName: newTaskData.applicationName,
      triggerType: newTaskData.timeStrategy === '定时' ? '定时触发' : newTaskData.timeStrategy === '周期' ? '周期触发' : '事件触发',
      priority: newTaskData.priority as Priority,
      scheduledTime: newTaskData.scheduledTime || new Date().toLocaleString('zh-CN'),
      status: '等待中',
      retryCount: 0,
      maxRetry: 3,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    onTaskCreated(newTask);
    onOpenChange(false);

    // 重置表单
    setNewTaskStep(1);
    setNewTaskData({
      name: '',
      applicationName: '',
      inputSources: {},
      priority: '',
      timeStrategy: '',
      scheduledTime: '',
      cronExpression: '',
      enableManualTrigger: false,
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Plus className="w-5 h-5 text-purple-600" />
            新增调度任务 - {['基本信息', '配置数据源', '调度策略'][newTaskStep - 1]}
          </DialogTitle>
          <DialogDescription>
            步骤 {newTaskStep} / 3
          </DialogDescription>
        </DialogHeader>

        {/* 步骤指示器 */}
        <div className="flex items-center justify-between mb-6">
          {[1, 2, 3].map((step) => (
            <div key={step} className="flex items-center">
              <div className="flex flex-col items-center">
                <div
                  className={`w-10 h-10 rounded-full flex items-center justify-center transition-all ${
                    step < newTaskStep
                      ? 'bg-green-500 text-white'
                      : step === newTaskStep
                      ? 'bg-purple-500 text-white'
                      : 'bg-gray-200 text-gray-500'
                  }`}
                >
                  {step < newTaskStep ? (
                    <CheckCircle className="w-5 h-5" />
                  ) : (
                    step
                  )}
                </div>
                <p className="text-xs mt-2 text-center">
                  {['基本信息', '配置数据源', '调度策略'][step - 1]}
                </p>
              </div>
              {step < 3 && (
                <div
                  className={`w-24 h-1 mx-2 ${
                    step < newTaskStep ? 'bg-green-500' : 'bg-gray-200'
                  }`}
                />
              )}
            </div>
          ))}
        </div>

        {/* 步骤1: 基本信息 */}
        {newTaskStep === 1 && (
          <div className="space-y-4">
            <Card className="p-4 bg-purple-50 border-purple-200 dark:bg-purple-950 dark:border-purple-800">
              <div className="flex items-center gap-2 text-purple-900 dark:text-purple-100">
                <FileText className="w-4 h-4" />
                <span className="text-sm">请填写调度任务的基本信息</span>
              </div>
            </Card>
            <div>
              <Label>任务名称 *</Label>
              <Input
                placeholder="请输入任务名称，如：每日灌溉计划生成"
                value={newTaskData.name}
                onChange={(e) => setNewTaskData({ ...newTaskData, name: e.target.value })}
              />
            </div>
            <div>
              <Label>选择应用 *</Label>
              <Select
                value={newTaskData.applicationName}
                onValueChange={(value) => setNewTaskData({ ...newTaskData, applicationName: value, inputSources: {} })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择要调度的应用" />
                </SelectTrigger>
                <SelectContent>
                  {applications.filter(app => app.status === '运行中').map((app) => (
                    <SelectItem key={app.id} value={app.name}>
                      <div className="flex items-center gap-2">
                        <span className="text-lg">{app.type === '智能灌溉' ? '💧' : app.type === '病虫害预警' ? '🐛' : app.type === '施肥推荐' ? '🌱' : '📊'}</span>
                        {app.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {selectedApplication && (
              <Card className="p-4 bg-blue-50 border-blue-200 dark:bg-blue-950 dark:border-blue-800">
                <div className="space-y-2 text-sm">
                  <p><strong>应用描述：</strong>{selectedApplication.description}</p>
                  <p><strong>使用模型：</strong>{selectedApplication.modelName} {selectedApplication.modelVersion}</p>
                  <p><strong>输入参数：</strong>{selectedApplication.inputConfig.fields.join('、')}</p>
                  <p><strong>输出格式：</strong>{selectedApplication.outputConfig.format}</p>
                </div>
              </Card>
            )}
          </div>
        )}

        {/* 步骤2: 配置数据源 */}
        {newTaskStep === 2 && selectedApplication && (
          <div className="space-y-4">
            <Card className="p-4 bg-blue-50 border-blue-200 dark:bg-blue-950 dark:border-blue-800">
              <div className="flex items-center gap-2 text-blue-900 dark:text-blue-100 text-sm">
                <AlertCircle className="w-4 h-4" />
                <span>请为应用的每个输入参数配置数据源</span>
              </div>
            </Card>
            <div className="space-y-4">
              {selectedApplication.inputConfig.fields.map((field) => (
                <Card key={field} className="p-4">
                  <div className="mb-3">
                    <Label className="flex items-center gap-2">
                      <span className="text-base">{field}</span>
                      <Badge variant="outline" className="text-xs">必填</Badge>
                    </Label>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label className="text-xs text-muted-foreground mb-2">多源数据</Label>
                      <Select
                        value={newTaskData.inputSources[field] || ''}
                        onValueChange={(value) =>
                          setNewTaskData({
                            ...newTaskData,
                            inputSources: { ...newTaskData.inputSources, [field]: value }
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择数据源" />
                        </SelectTrigger>
                        <SelectContent>
                          {dataSourceOptions.map((source) => (
                            <SelectItem key={source} value={source}>
                              {source}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label className="text-xs text-muted-foreground mb-2">物联设备数据</Label>
                      <Select
                        value={newTaskData.inputSources[field] || ''}
                        onValueChange={(value) =>
                          setNewTaskData({
                            ...newTaskData,
                            inputSources: { ...newTaskData.inputSources, [field]: value }
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择物联设备" />
                        </SelectTrigger>
                        <SelectContent>
                          {iotDeviceOptions.map((device) => (
                            <SelectItem key={device} value={device}>
                              {device}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        )}

        {/* 步骤3: 调度策略 */}
        {newTaskStep === 3 && (
          <div className="space-y-4">
            <Card className="p-4 bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800">
              <div className="flex items-center gap-2 text-green-900 dark:text-green-100 text-sm">
                <Timer className="w-4 h-4" />
                <span>配置任务的调度策略和执行时间</span>
              </div>
            </Card>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>优先级 *</Label>
                <Select
                  value={newTaskData.priority}
                  onValueChange={(value) => setNewTaskData({ ...newTaskData, priority: value as Priority })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择优先级" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="高">高</SelectItem>
                    <SelectItem value="中">中</SelectItem>
                    <SelectItem value="低">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>时间策略 *</Label>
                <Select
                  value={newTaskData.timeStrategy}
                  onValueChange={(value) => setNewTaskData({ ...newTaskData, timeStrategy: value as any })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择时间策略" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="定时">定时</SelectItem>
                    <SelectItem value="周期">周期</SelectItem>
                    <SelectItem value="每天">每天</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {newTaskData.timeStrategy === '定时' && (
              <div>
                <Label>定时执行时间 *</Label>
                <Input
                  type="datetime-local"
                  value={newTaskData.scheduledTime}
                  onChange={(e) => setNewTaskData({ ...newTaskData, scheduledTime: e.target.value })}
                />
              </div>
            )}

            {newTaskData.timeStrategy === '周期' && (
              <div>
                <Label>周期表达式 *</Label>
                <Input
                  placeholder="如: 0 */6 * * * (每6小时执行一次)"
                  value={newTaskData.cronExpression}
                  onChange={(e) => setNewTaskData({ ...newTaskData, cronExpression: e.target.value })}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  支持标准Cron表达式格式：分 时 日 月 星期
                </p>
              </div>
            )}

            {newTaskData.timeStrategy === '每天' && (
              <div>
                <Label>每日执行时间 *</Label>
                <Input
                  type="time"
                  value={newTaskData.scheduledTime?.split(' ')[1] || ''}
                  onChange={(e) => setNewTaskData({ ...newTaskData, scheduledTime: e.target.value })}
                />
              </div>
            )}

            <div className="flex items-center gap-2">
              <Checkbox
                id="manual-trigger"
                checked={newTaskData.enableManualTrigger}
                onCheckedChange={(checked) => setNewTaskData({ ...newTaskData, enableManualTrigger: checked as boolean })}
              />
              <Label htmlFor="manual-trigger">启用手动触发功能</Label>
            </div>
          </div>
        )}

        <DialogFooter>
          <div className="flex justify-between w-full">
            <div>
              {newTaskStep > 1 && (
                <Button variant="outline" onClick={handleNewTaskPrevStep}>
                  上一步
                </Button>
              )}
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => onOpenChange(false)}>
                取消
              </Button>
              {newTaskStep < 3 ? (
                <Button onClick={handleNewTaskNextStep}>
                  下一步
                </Button>
              ) : (
                <Button onClick={handleCreateTask}>
                  <Rocket className="w-4 h-4 mr-2" />
                  创建任务
                </Button>
              )}
            </div>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}