import { useState, useEffect } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../../ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Plus, AlertCircle, Edit, Trash2, GripVertical, Eye, Filter, XCircle } from 'lucide-react';
import { Task, Field, TaskStatus } from '../../../types/task';
import { MachineryRecord } from '../../../types/machinery';
import { Driver } from '../../../types/driver';
import { machineryStorage } from '../../../lib/machineryStorage';
import { TaskForm } from './TaskForm';
import { TaskStatusManager } from './TaskStatusManager';
import { TaskCancelDialog } from './TaskCancelDialog';
import { toast } from 'sonner@2.0.3';

// 拖拽类型定义
const ItemTypes = {
  MACHINERY: 'machinery',
  DRIVER: 'driver',
};

// 可拖拽的资源卡片
function DraggableResource({ type, data }: { type: string; data: MachineryRecord | Driver }) {
  const [collected, drag] = useDrag(() => ({
    type,
    item: { id: data.id, name: 'name' in data ? data.name : '', type },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  const isDragging = collected.isDragging;
  const isMachinery = type === ItemTypes.MACHINERY;
  const machinery = isMachinery ? (data as MachineryRecord) : null;
  const driver = !isMachinery ? (data as Driver) : null;

  const dragClassName = isDragging 
    ? 'p-3 border rounded-lg cursor-move transition-all opacity-50 scale-95 border-success bg-success-muted'
    : 'p-3 border rounded-lg cursor-move transition-all hover:border-success/50 hover:shadow-sm';

  const badgeClassName = machinery?.status === '维修中' ? 'bg-warning-muted text-warning-muted-foreground' : '';

  return (
    <div ref={drag} className={dragClassName}>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 flex-1">
          <GripVertical className="w-4 h-4 text-muted-foreground" />
          <div>
            <div className="text-sm">{machinery?.name || driver?.name}</div>
            <div className="text-xs text-muted-foreground">
              {machinery?.model || driver?.phone}
            </div>
          </div>
        </div>
        <Badge variant="secondary" className={badgeClassName}>
          {machinery?.status || (driver?.status === 'active' ? '空闲' : driver?.status)}
        </Badge>
      </div>
    </div>
  );
}

// 可放置的任务卡片
function DroppableTaskCard({ 
  task, 
  onDrop, 
  onEdit, 
  onDelete,
  onView,
  onCancel,
  getPriorityColor,
  getPriorityText,
  getTaskStatusColor 
}: { 
  task: Task; 
  onDrop: (taskId: string, item: { id: string; type: string; name: string }) => void;
  onEdit: (task: Task) => void;
  onDelete: (taskId: string) => void;
  onView: (task: Task) => void;
  onCancel: (task: Task) => void;
  getPriorityColor: (priority: string) => string;
  getPriorityText: (priority: string) => string;
  getTaskStatusColor: (status: string) => string;
}) {
  const [collected, drop] = useDrop(() => ({
    accept: [ItemTypes.MACHINERY, ItemTypes.DRIVER],
    drop: (item: { id: string; type: string; name: string }) => {
      onDrop(task.id, item);
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  }));

  const isOver = collected.isOver;
  const canDrop = collected.canDrop;

  let cardClassName = 'p-4 transition-all';
  if (isOver && canDrop) {
    cardClassName = 'p-4 transition-all border-success bg-success-muted shadow-lg scale-[1.02]';
  } else if (canDrop) {
    cardClassName = 'p-4 transition-all border-success/50';
  }

  return (
    <div ref={drop}>
      <Card className={cardClassName}>
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <div className="flex items-center gap-3 mb-2">
              <h4 className="text-base">{task.name}</h4>
              <Badge variant="secondary" className={getPriorityColor(task.priority)}>
                {getPriorityText(task.priority)}
              </Badge>
              <Badge variant="secondary" className={getTaskStatusColor(task.status)}>
                {task.status}
              </Badge>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm mb-2">
              <div>
                <span className="text-muted-foreground">任务类型:</span>
                <span className="ml-2">{task.taskType}</span>
              </div>
              {task.fieldName && (
                <div>
                  <span className="text-muted-foreground">地块:</span>
                  <span className="ml-2">{task.fieldName}</span>
                </div>
              )}
              <div>
                <span className="text-muted-foreground">开始时间:</span>
                <span className="ml-2">
                  {new Date(task.startTime).toLocaleString('zh-CN', {
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                  })}
                </span>
              </div>
              <div>
                <span className="text-muted-foreground">预计时长:</span>
                <span className="ml-2">{task.estimatedDuration}小时</span>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <span className="text-muted-foreground">农机:</span>
                <span className={!task.machineryName ? 'ml-2 text-warning' : 'ml-2'}>
                  {task.machineryName || '未分配'}
                </span>
              </div>
              <div>
                <span className="text-muted-foreground">驾驶员:</span>
                <span className={!task.driverName ? 'ml-2 text-warning' : 'ml-2'}>
                  {task.driverName || '未分配'}
                </span>
              </div>
            </div>
            {isOver && canDrop && (
              <div className="mt-2 text-sm text-success flex items-center gap-2">
                <AlertCircle className="w-4 h-4" />
                <span>释放以分配资源</span>
              </div>
            )}
          </div>
          <div className="flex gap-2 ml-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => onView(task)}
              title="查看详情"
            >
              <Eye className="w-4 h-4" />
            </Button>
            {task.status !== '已完成' && task.status !== '已取消' && (
              <>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => onEdit(task)}
                  title="编辑任务"
                >
                  <Edit className="w-4 h-4" />
                </Button>
                {task.status !== '进行中' && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => onDelete(task.id)}
                    title="删除任务"
                  >
                    <Trash2 className="w-4 h-4 text-destructive" />
                  </Button>
                )}
                {(task.status === '待分配' || task.status === '已分配' || task.status === '进行中') && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => onCancel(task)}
                    title="取消任务"
                    className="text-error hover:text-error/90 hover:bg-error-muted"
                  >
                    <XCircle className="w-4 h-4" />
                  </Button>
                )}
              </>
            )}
          </div>
        </div>
      </Card>
    </div>
  );
}

export function TaskAssignment() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [fields, setFields] = useState<Field[]>([]);
  const [showTaskForm, setShowTaskForm] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [showTaskDetail, setShowTaskDetail] = useState(false);
  const [statusFilter, setStatusFilter] = useState<TaskStatus | 'all'>('all');
  const [cancelingTask, setCancelingTask] = useState<Task | null>(null);
  const [showCancelDialog, setShowCancelDialog] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    // 加载农机数据
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    // 加载驾驶员数据
    const driversData = localStorage.getItem('smart_agriculture_drivers');
    if (driversData) {
      setDrivers(JSON.parse(driversData));
    } else {
      // 初始化示例驾驶员数据
      const mockDrivers: Driver[] = [
        {
          id: 'driver-1',
          name: '张三',
          phone: '13800138001',
          idCard: '110101199001011234',
          driverLicense: 'A1',
          licenseExpiry: '2026-06-30',
          status: 'active',
          hireDate: '2020-03-15',
          experience: 5,
          specialties: ['拖拉机', '收割机'],
          createdAt: new Date().toISOString(),
        },
        {
          id: 'driver-2',
          name: '李四',
          phone: '13800138002',
          idCard: '110101199002021234',
          driverLicense: 'B2',
          licenseExpiry: '2025-12-31',
          status: 'active',
          hireDate: '2021-05-20',
          experience: 3,
          specialties: ['播种机', '施肥机'],
          createdAt: new Date().toISOString(),
        },
        {
          id: 'driver-3',
          name: '王五',
          phone: '13800138003',
          idCard: '110101199003031234',
          driverLicense: 'A2',
          licenseExpiry: '2027-03-15',
          status: 'active',
          hireDate: '2019-08-10',
          experience: 8,
          specialties: ['拖拉机', '收割机', '喷药机'],
          createdAt: new Date().toISOString(),
        },
        {
          id: 'driver-4',
          name: '赵六',
          phone: '13800138004',
          idCard: '110101199004041234',
          driverLicense: 'B1',
          licenseExpiry: '2026-09-20',
          status: 'active',
          hireDate: '2022-01-15',
          experience: 2,
          specialties: ['拖拉机'],
          createdAt: new Date().toISOString(),
        },
        {
          id: 'driver-5',
          name: '孙七',
          phone: '13800138005',
          idCard: '110101199005051234',
          driverLicense: 'A1',
          licenseExpiry: '2025-08-30',
          status: 'active',
          hireDate: '2018-06-01',
          experience: 10,
          specialties: ['拖拉机', '收割机', '播种机', '施肥机'],
          createdAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem('smart_agriculture_drivers', JSON.stringify(mockDrivers));
      setDrivers(mockDrivers);
    }

    // 加载地块数据（模拟）
    const mockFields: Field[] = [
      { id: 'field-1', name: '1号地块', area: 50, location: '东区', cropType: '小麦', status: 'idle' },
      { id: 'field-2', name: '2号地块', area: 80, location: '西区', cropType: '玉米', status: 'idle' },
      { id: 'field-3', name: '3号地块', area: 35, location: '南区', cropType: '水稻', status: 'idle' },
      { id: 'field-4', name: '4号地块', area: 60, location: '北区', cropType: '大豆', status: 'idle' },
    ];
    setFields(mockFields);

    // 加载任务数据
    const tasksData = localStorage.getItem('smart_agriculture_tasks');
    if (tasksData) {
      setTasks(JSON.parse(tasksData));
    } else {
      // 初始化示例任务
      const mockTasks: Task[] = [
        {
          id: 'task-1',
          name: '1号地块耕地作业',
          taskType: '耕地',
          priority: 'high',
          fieldId: 'field-1',
          fieldName: '1号地块',
          fieldArea: 50,
          machineryId: machineryData[0]?.id || null,
          machineryName: machineryData[0]?.name,
          driverId: null,
          startTime: '2024-10-13T08:00',
          endTime: '2024-10-13T17:00',
          estimatedDuration: 9,
          status: '待分配',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          createdBy: '系统管理员',
        },
        {
          id: 'task-2',
          name: '2号地块播种',
          taskType: '播种',
          priority: 'medium',
          fieldId: 'field-2',
          fieldName: '2号地块',
          fieldArea: 80,
          machineryId: null,
          driverId: null,
          startTime: '2024-10-14T07:00',
          endTime: '2024-10-14T18:00',
          estimatedDuration: 11,
          status: '待分配',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          createdBy: '系统管理员',
        },
      ];
      localStorage.setItem('smart_agriculture_tasks', JSON.stringify(mockTasks));
      setTasks(mockTasks);
    }
  };

  const handleSaveTask = (taskData: Partial<Task>) => {
    if (editingTask) {
      // 更新任务
      const updated: Task = {
        ...editingTask,
        ...taskData,
        updatedAt: new Date().toISOString(),
        updatedBy: '系统管理员',
      };
      const newTasks = tasks.map(t => t.id === updated.id ? updated : t);
      setTasks(newTasks);
      localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
      toast.success('任务更新成功');
    } else {
      // 创建新任务
      const newTask: Task = {
        id: `task-${Date.now()}`,
        ...taskData as Task,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: '系统管理员',
      };
      const newTasks = [...tasks, newTask];
      setTasks(newTasks);
      localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
      toast.success('任务创建成功');
    }
    setShowTaskForm(false);
    setEditingTask(null);
  };

  const handleEditTask = (task: Task) => {
    setEditingTask(task);
    setShowTaskForm(true);
  };

  const handleDeleteTask = (taskId: string) => {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;

    // 如果任务正在进行中，提示先取消
    if (task.status === '进行中') {
      toast.error('请先取消或完成正在进行中的任务，再删除');
      return;
    }

    if (confirm(`确定要删除任务"${task.name}"吗？此操作不可撤销。`)) {
      const newTasks = tasks.filter(t => t.id !== taskId);
      setTasks(newTasks);
      localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
      toast.success('任务已删除');
    }
  };

  const handleAssignResources = (taskId: string, machineryId: string | null, driverId: string | null) => {
    const newTasks = tasks.map(t => {
      if (t.id === taskId) {
        const machineryData = machinery.find(m => m.id === machineryId);
        const driverData = drivers.find(d => d.id === driverId);
        return {
          ...t,
          machineryId,
          machineryName: machineryData?.name,
          driverId,
          driverName: driverData?.name,
          status: (machineryId && driverId ? '已分配' : '待分配') as Task['status'],
          updatedAt: new Date().toISOString(),
        };
      }
      return t;
    });
    setTasks(newTasks);
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
    toast.success('资源分配成功');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '空闲': return 'bg-success-muted text-success-muted-foreground';
      case '作业中': return 'bg-info-muted text-info-muted-foreground';
      case '维修中': return 'bg-warning-muted text-warning-muted-foreground';
      case '休假': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent': return 'bg-error-muted text-error-muted-foreground';
      case 'high': return 'bg-warning-muted text-warning-muted-foreground';
      case 'medium': return 'bg-warning-muted text-warning-muted-foreground';
      case 'low': return 'bg-info-muted text-info-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getPriorityText = (priority: string) => {
    switch (priority) {
      case 'urgent': return '紧急';
      case 'high': return '高';
      case 'medium': return '中';
      case 'low': return '低';
      default: return priority;
    }
  };

  const getTaskStatusColor = (status: string) => {
    switch (status) {
      case '已完成': return 'bg-success-muted text-success';
      case '进行中': return 'bg-info-muted text-info';
      case '已分配': return 'bg-accent-muted text-accent';
      case '待分配': return 'bg-warning-muted text-warning';
      case '已取消': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  // 处理拖拽分配
  const handleDragDrop = (taskId: string, item: { id: string; type: string; name: string }) => {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;

    if (item.type === ItemTypes.MACHINERY) {
      handleAssignResources(taskId, item.id, task.driverId);
      toast.success(`已将农机"${item.name}"分配到任务"${task.name}"`);
    } else if (item.type === ItemTypes.DRIVER) {
      handleAssignResources(taskId, task.machineryId, item.id);
      toast.success(`已将驾驶员"${item.name}"分配到任务"${task.name}"`);
    }
  };

  // 处理任务状态变更
  const handleTaskStatusChange = (taskId: string, newStatus: TaskStatus, note?: string) => {
    const newTasks = tasks.map(t => {
      if (t.id === taskId) {
        return {
          ...t,
          status: newStatus,
          updatedAt: new Date().toISOString(),
          updatedBy: '系统管理员',
        };
      }
      return t;
    });
    setTasks(newTasks);
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
    
    const statusMessages: Record<TaskStatus, string> = {
      '待分配': '任务已重置为待分配状态',
      '已分配': '任务已确认分配',
      '进行中': '任务已开始执行',
      '已完成': '任务已完成',
      '已取消': '任务已取消',
    };
    
    toast.success(statusMessages[newStatus] || '任务状态已更新');
    
    // 更新选中的任务
    if (selectedTask && selectedTask.id === taskId) {
      setSelectedTask(newTasks.find(t => t.id === taskId) || null);
    }
  };

  // 查看任务详情
  const handleViewTask = (task: Task) => {
    setSelectedTask(task);
    setShowTaskDetail(true);
  };

  // 取消任务
  const handleCancelTask = (task: Task) => {
    setCancelingTask(task);
    setShowCancelDialog(true);
  };

  // 确认取消任务
  const handleConfirmCancel = (taskId: string, reason: string) => {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;

    const newTasks = tasks.map(t => {
      if (t.id === taskId) {
        return {
          ...t,
          status: '已取消' as TaskStatus,
          remarks: t.remarks 
            ? `${t.remarks}\n\n【取消原因】${reason}\n取消时间: ${new Date().toLocaleString('zh-CN')}`
            : `【取消原因】${reason}\n取消时间: ${new Date().toLocaleString('zh-CN')}`,
          updatedAt: new Date().toISOString(),
          updatedBy: '系统管理员',
        };
      }
      return t;
    });

    setTasks(newTasks);
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(newTasks));
    
    toast.success(`任务"${task.name}"已取消`);
    
    // 更新选中的任务
    if (selectedTask && selectedTask.id === taskId) {
      setSelectedTask(newTasks.find(t => t.id === taskId) || null);
    }
  };

  // 过滤任务
  const filteredTasks = statusFilter === 'all' 
    ? tasks 
    : tasks.filter(t => t.status === statusFilter);

  return (
    <DndProvider backend={HTML5Backend}>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-primary">任务分配</h2>
            <p className="text-muted-foreground">可视化管理任务分配和资源调度</p>
          </div>
          <Button onClick={() => {
            setEditingTask(null);
            setShowTaskForm(true);
          }}>
            <Plus className="w-4 h-4 mr-2" />
            创建任务
          </Button>
        </div>

        {/* 统计 */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          <Card className="p-4">
            <div className="text-sm text-muted-foreground">总任务数</div>
            <div className="mt-1">{tasks.length}</div>
          </Card>
          <Card className="p-4">
            <div className="text-sm text-muted-foreground">待分配</div>
            <div className="mt-1 text-warning">
              {tasks.filter(t => t.status === '待分配').length}
            </div>
          </Card>
          <Card className="p-4">
            <div className="text-sm text-muted-foreground">已分配</div>
            <div className="mt-1 text-accent">
              {tasks.filter(t => t.status === '已分配').length}
            </div>
          </Card>
          <Card className="p-4">
            <div className="text-sm text-muted-foreground">空闲农机</div>
            <div className="mt-1 text-success">
              {machinery.filter(m => m.status !== '维修中').length}
            </div>
          </Card>
          <Card className="p-4">
            <div className="text-sm text-muted-foreground">空闲驾驶员</div>
            <div className="mt-1 text-success">
              {drivers.filter(d => d.status === 'active').length}
            </div>
          </Card>
        </div>

        {/* 任务列表 */}
        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h3>任务列表</h3>
            <div className="flex items-center gap-4">
              {/* 状态筛选 */}
              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4 text-muted-foreground" />
                <Tabs value={statusFilter} onValueChange={(v) => setStatusFilter(v as TaskStatus | 'all')}>
                  <TabsList>
                    <TabsTrigger value="all">全部 ({tasks.length})</TabsTrigger>
                    <TabsTrigger value="待分配">待分配 ({tasks.filter(t => t.status === '待分配').length})</TabsTrigger>
                    <TabsTrigger value="已分配">已分配 ({tasks.filter(t => t.status === '已分配').length})</TabsTrigger>
                    <TabsTrigger value="进行中">进行中 ({tasks.filter(t => t.status === '进行中').length})</TabsTrigger>
                    <TabsTrigger value="已完成">已完成 ({tasks.filter(t => t.status === '已完成').length})</TabsTrigger>
                    <TabsTrigger value="已取消">已取消 ({tasks.filter(t => t.status === '已取消').length})</TabsTrigger>
                  </TabsList>
                </Tabs>
              </div>
              <div className="text-sm text-muted-foreground flex items-center gap-2">
                <GripVertical className="w-4 h-4" />
                <span>拖拽资源到任务卡片分配</span>
              </div>
            </div>
          </div>
          <div className="space-y-3">
            {filteredTasks.length === 0 ? (
              <div className="text-center text-muted-foreground py-8">
                {statusFilter === 'all' ? '暂无任务，点击"创建任务"开始添加' : `暂无${statusFilter}状态的任务`}
              </div>
            ) : (
              filteredTasks.map(task => (
                <DroppableTaskCard
                  key={task.id}
                  task={task}
                  onDrop={handleDragDrop}
                  onEdit={handleEditTask}
                  onDelete={handleDeleteTask}
                  onView={handleViewTask}
                  onCancel={handleCancelTask}
                  getPriorityColor={getPriorityColor}
                  getPriorityText={getPriorityText}
                  getTaskStatusColor={getTaskStatusColor}
                />
              ))
            )}
          </div>
        </Card>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 农机资源 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>农机资源</h3>
              <Badge variant="outline" className="text-xs">
                可拖拽
              </Badge>
            </div>
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {machinery.length === 0 ? (
                <div className="text-center text-muted-foreground py-4">
                  暂无农机
                </div>
              ) : (
                machinery.map(m => (
                  <DraggableResource
                    key={m.id}
                    type={ItemTypes.MACHINERY}
                    data={m}
                  />
                ))
              )}
            </div>
          </Card>

          {/* 驾驶员资源 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>驾驶员资源</h3>
              <Badge variant="outline" className="text-xs">
                可拖拽
              </Badge>
            </div>
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {drivers.length === 0 ? (
                <div className="text-center text-muted-foreground py-4">
                  暂无驾驶员
                </div>
              ) : (
                drivers.map(d => (
                  <DraggableResource
                    key={d.id}
                    type={ItemTypes.DRIVER}
                    data={d}
                  />
                ))
              )}
            </div>
          </Card>
        </div>

        {/* 功能说明 */}
        <Card className="p-6 bg-info-muted border-info">
          <h4 className="mb-3 text-muted-foreground">任务分配功能</h4>
          <ul className="space-y-2 text-sm text-muted-foreground">
            <li>• <strong>拖拽分配</strong>：从资源面板拖拽农机或驾驶员到任务卡片即可快速分配</li>
            <li>• <strong>智能冲突检测</strong>：自动检测农机、驾驶员、地块的时间冲突</li>
            <li>• <strong>优先级管理</strong>：支持紧急、高、中、低四级优先级</li>
            <li>• <strong>灵活分配</strong>：可选择立即分配或稍后分配资源</li>
            <li>• <strong>实时更新</strong>：任务变更实时保存和通知</li>
          </ul>
        </Card>

        {/* 任务创建表单 */}
        <TaskForm
          open={showTaskForm}
          onClose={() => {
            setShowTaskForm(false);
            setEditingTask(null);
          }}
          onSave={handleSaveTask}
          editingTask={editingTask}
          machinery={machinery}
          drivers={drivers}
          fields={fields}
          existingTasks={tasks}
        />

        {/* 任务详情对话框 */}
        <Dialog open={showTaskDetail} onOpenChange={setShowTaskDetail}>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>任务详情</DialogTitle>
              <DialogDescription>
                查看和管理任务状态
              </DialogDescription>
            </DialogHeader>

            {selectedTask && (
              <div className="space-y-6">
                {/* 任务状态管理 */}
                <TaskStatusManager
                  task={selectedTask}
                  onStatusChange={handleTaskStatusChange}
                />

                {/* 任务基本信息 */}
                <Card className="p-4">
                  <h4 className="mb-4">基本信息</h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">任务名称:</span>
                      <span className="ml-2">{selectedTask.name}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">任务类型:</span>
                      <span className="ml-2">{selectedTask.taskType}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">优先级:</span>
                      <Badge className={getPriorityColor(selectedTask.priority)} variant="secondary">
                        {getPriorityText(selectedTask.priority)}
                      </Badge>
                    </div>
                    <div>
                      <span className="text-muted-foreground">地块:</span>
                      <span className="ml-2">{selectedTask.fieldName || '-'}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">开始时间:</span>
                      <span className="ml-2">
                        {new Date(selectedTask.startTime).toLocaleString('zh-CN')}
                      </span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">结束时间:</span>
                      <span className="ml-2">
                        {new Date(selectedTask.endTime).toLocaleString('zh-CN')}
                      </span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">预计时长:</span>
                      <span className="ml-2">{selectedTask.estimatedDuration} 小时</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">创建人:</span>
                      <span className="ml-2">{selectedTask.createdBy}</span>
                    </div>
                  </div>
                  {selectedTask.description && (
                    <div className="mt-4">
                      <span className="text-muted-foreground">任务描述:</span>
                      <p className="mt-2 text-sm">{selectedTask.description}</p>
                    </div>
                  )}
                </Card>

                {/* 作业要求 */}
                {selectedTask.requirements && Object.keys(selectedTask.requirements).length > 0 && (
                  <Card className="p-4">
                    <h4 className="mb-4">作业要求</h4>
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      {selectedTask.requirements.workingDepth && (
                        <div>
                          <span className="text-muted-foreground">作业深度:</span>
                          <span className="ml-2">{selectedTask.requirements.workingDepth} cm</span>
                        </div>
                      )}
                      {selectedTask.requirements.workingSpeed && (
                        <div>
                          <span className="text-muted-foreground">作业速度:</span>
                          <span className="ml-2">{selectedTask.requirements.workingSpeed} km/h</span>
                        </div>
                      )}
                      {selectedTask.requirements.seedingRate && (
                        <div>
                          <span className="text-muted-foreground">播种量:</span>
                          <span className="ml-2">{selectedTask.requirements.seedingRate} kg/亩</span>
                        </div>
                      )}
                      {selectedTask.requirements.fertilizingRate && (
                        <div>
                          <span className="text-muted-foreground">施肥量:</span>
                          <span className="ml-2">{selectedTask.requirements.fertilizingRate} kg/亩</span>
                        </div>
                      )}
                      {selectedTask.requirements.quality && (
                        <div>
                          <span className="text-muted-foreground">质量要求:</span>
                          <span className="ml-2">{selectedTask.requirements.quality}</span>
                        </div>
                      )}
                    </div>
                  </Card>
                )}

                {/* 备注 */}
                {selectedTask.remarks && (
                  <Card className="p-4">
                    <h4 className="mb-2">备注</h4>
                    <p className="text-sm text-muted-foreground">{selectedTask.remarks}</p>
                  </Card>
                )}
              </div>
            )}
          </DialogContent>
        </Dialog>

        {/* 取消任务对话框 */}
        <TaskCancelDialog
          open={showCancelDialog}
          task={cancelingTask}
          onClose={() => {
            setShowCancelDialog(false);
            setCancelingTask(null);
          }}
          onConfirm={handleConfirmCancel}
        />
      </div>
    </DndProvider>
  );
}
