import { useState, useEffect, useRef } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '../../ui/dialog';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Textarea } from '../../ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Alert, AlertDescription } from '../../ui/alert';
import { 
  MapPin, Activity, AlertTriangle, RefreshCw,
  Users, Tractor, Pause, Play, RotateCcw,
  Zap, CloudRain, Wrench, Clock, CheckCircle2, XCircle,
  TrendingUp, Bell, ChevronRight
} from 'lucide-react';
import { Task, TaskStatus } from '../../../types/task';
import { MachineryRecord } from '../../../types/machinery';
import { Driver } from '../../../types/driver';
import { machineryStorage } from '../../../lib/machineryStorage';
import { loadAMapScript, isAMapLoaded } from '../../../lib/mapLoader';
import { toast } from 'sonner@2.0.3';

// 突发事件类型
interface EmergencyEvent {
  id: string;
  type: 'fault' | 'weather' | 'urgent' | 'other';
  severity: 'low' | 'medium' | 'high' | 'critical';
  title: string;
  description: string;
  affectedMachineryIds: string[];
  affectedTaskIds: string[];
  timestamp: string;
  status: 'pending' | 'handling' | 'resolved';
  resolution?: string;
}

// 调度变更记录
interface DispatchChange {
  id: string;
  type: 'reassign' | 'priority' | 'order' | 'pause' | 'resume' | 'emergency';
  taskId: string;
  taskName: string;
  description: string;
  operator: string;
  timestamp: string;
  details: any;
}

// 高德地图类型声明
declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: any;
  }
}

export function RealtimeDispatch() {
  // 数据状态
  const [tasks, setTasks] = useState<Task[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [emergencyEvents, setEmergencyEvents] = useState<EmergencyEvent[]>([]);
  const [dispatchChanges, setDispatchChanges] = useState<DispatchChange[]>([]);

  // UI状态
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [showReassignDialog, setShowReassignDialog] = useState(false);
  const [showPriorityDialog, setShowPriorityDialog] = useState(false);
  const [showHistoryDialog, setShowHistoryDialog] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<EmergencyEvent | null>(null);
  
  // 表单状态
  const [newMachineryId, setNewMachineryId] = useState<string>('keep-current');
  const [newDriverId, setNewDriverId] = useState<string>('keep-current');
  const [newPriority, setNewPriority] = useState<string>('');

  // 地图状态
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<any>(null);
  const markersRef = useRef<Map<string, any>>(new Map());
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(true);

  // 加载数据
  useEffect(() => {
    loadData();
    initializeMap();

    // 自动刷新（每10秒）
    const interval = setInterval(() => {
      if (autoRefresh) {
        refreshData();
      }
    }, 10000);

    return () => {
      clearInterval(interval);
      if (mapRef.current) {
        mapRef.current.destroy();
      }
    };
  }, []);

  // 加载基础数据
  const loadData = () => {
    // 加载任务
    const savedTasks = localStorage.getItem('smart_agriculture_tasks');
    let allTasks: Task[] = [];
    
    if (savedTasks) {
      allTasks = JSON.parse(savedTasks);
    }
    
    // 如果没有执行中的任务，添加一个示例任务
    const activeTasks = allTasks.filter((t: Task) => 
      t.status === '已分配' || t.status === '进行中'
    );
    
    if (activeTasks.length === 0) {
      // 创建示例任务
      const sampleTask: Task = {
        id: `sample-task-${Date.now()}`,
        name: '1号地块春耕作业',
        description: '进行春季耕地作业，深度25cm',
        taskType: '耕地',
        priority: 'high',
        fieldId: 'field-1',
        fieldName: '1号示范田',
        fieldArea: 50,
        machineryId: '1',
        machineryName: '约翰迪尔拖拉机',
        driverId: 'driver-1',
        driverName: '张师傅',
        startTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2小时前开始
        endTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(), // 预计2小时后结束
        estimatedDuration: 4,
        requirements: {
          workingDepth: 25,
          workingSpeed: 6,
          quality: '优'
        },
        status: '进行中',
        remarks: '注意保持作业深度均匀',
        createdAt: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString(),
        updatedAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        createdBy: '系统管理员',
        updatedBy: '调度员'
      };
      
      allTasks.push(sampleTask);
      localStorage.setItem('smart_agriculture_tasks', JSON.stringify(allTasks));
      activeTasks.push(sampleTask);
    }
    
    setTasks(activeTasks);

    // 加载农机
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    // 加载驾驶员
    const savedDrivers = localStorage.getItem('drivers');
    if (savedDrivers) {
      setDrivers(JSON.parse(savedDrivers));
    }

    // 加载突发事件
    const savedEvents = localStorage.getItem('smart_agriculture_emergency_events');
    if (savedEvents) {
      setEmergencyEvents(JSON.parse(savedEvents));
    } else {
      // 初始化示例事件
      const initialEvents: EmergencyEvent[] = [
        {
          id: 'event-1',
          type: 'fault',
          severity: 'high',
          title: '约翰迪尔拖拉机液压系统异常',
          description: '液压油压力下降，建议立即检修',
          affectedMachineryIds: ['1'],
          affectedTaskIds: [],
          timestamp: new Date().toISOString(),
          status: 'pending',
        }
      ];
      setEmergencyEvents(initialEvents);
      localStorage.setItem('smart_agriculture_emergency_events', JSON.stringify(initialEvents));
    }

    // 加载调度变更历史
    const savedChanges = localStorage.getItem('smart_agriculture_dispatch_changes');
    if (savedChanges) {
      setDispatchChanges(JSON.parse(savedChanges));
    }
  };

  // 刷新数据
  const refreshData = () => {
    const savedTasks = localStorage.getItem('smart_agriculture_tasks');
    if (savedTasks) {
      const allTasks = JSON.parse(savedTasks);
      setTasks(allTasks.filter((t: Task) => 
        t.status === '已分配' || t.status === '进行中'
      ));
    }
    
    // 更新地图标记
    if (isMapLoaded) {
      updateMapMarkers();
    }
  };

  // 初始化地图
  const initializeMap = () => {
    if (!isAMapLoaded()) {
      loadAMapScript()
        .then(() => {
          createMap();
        })
        .catch(() => {
          // 静默失败，使用占位地图
        });
    } else {
      createMap();
    }
  };

  // 创建地图
  const createMap = () => {
    if (!mapContainerRef.current || !window.AMap) return;

    try {
      const map = new window.AMap.Map(mapContainerRef.current, {
        zoom: 13,
        center: [117.1201, 36.6512],
        mapStyle: 'amap://styles/normal',
      });

      mapRef.current = map;
      setIsMapLoaded(true);
      updateMapMarkers();
    } catch (error) {
      console.log('ℹ️ 使用占位地图模式');
      setIsMapLoaded(true);
    }
  };

  // 更新地图标记
  const updateMapMarkers = () => {
    if (!mapRef.current || !window.AMap) return;

    // 清除旧标记
    markersRef.current.forEach(marker => marker.setMap(null));
    markersRef.current.clear();

    // 为每个任务添加标记
    tasks.forEach(task => {
      if (!task.machineryId) return;

      // 模拟位置（实际应从GPS数据获取）
      const index = tasks.indexOf(task);
      const position = [
        117.1201 + (index * 0.01),
        36.6512 + (index * 0.01)
      ];

      const marker = new window.AMap.Marker({
        position: position,
        title: task.machineryName || '农机',
        content: createMarkerContent(task),
      });

      marker.on('click', () => {
        setSelectedTask(task);
      });

      marker.setMap(mapRef.current);
      markersRef.current.set(task.id, marker);
    });
  };

  // 创建标记内容
  const createMarkerContent = (task: Task) => {
    const statusColor = task.status === '进行中' ? '#22c55e' : '#3b82f6';
    return `
      <div style="
        background: white;
        padding: 8px 12px;
        border-radius: 8px;
        border: 2px solid ${statusColor};
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        font-size: 12px;
        white-space: nowrap;
      ">
        <div style="font-weight: bold; color: ${statusColor};">${task.machineryName}</div>
        <div style="color: #666; margin-top: 4px;">${task.name}</div>
      </div>
    `;
  };

  // 任务重新指派
  const handleReassignTask = () => {
    if (!selectedTask || ((!newMachineryId || newMachineryId === 'keep-current') && (!newDriverId || newDriverId === 'keep-current'))) {
      toast.error('请选择要更换的农机或驾驶员');
      return;
    }

    const updatedTask = { ...selectedTask };
    let changeDescription = '';

    if (newMachineryId && newMachineryId !== 'keep-current') {
      const newMachinery = machinery.find(m => m.id === newMachineryId);
      if (newMachinery) {
        updatedTask.machineryId = newMachinery.id;
        updatedTask.machineryName = newMachinery.name;
        changeDescription += `农机: ${selectedTask.machineryName} → ${newMachinery.name}`;
      }
    }

    if (newDriverId && newDriverId !== 'keep-current') {
      const newDriver = drivers.find(d => d.id === newDriverId);
      if (newDriver) {
        updatedTask.driverId = newDriver.id;
        updatedTask.driverName = newDriver.name;
        if (changeDescription) changeDescription += '; ';
        changeDescription += `驾驶员: ${selectedTask.driverName} → ${newDriver.name}`;
      }
    }

    // 更新任务
    const allTasks = JSON.parse(localStorage.getItem('smart_agriculture_tasks') || '[]');
    const updatedTasks = allTasks.map((t: Task) => 
      t.id === updatedTask.id ? updatedTask : t
    );
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(updatedTasks));
    
    // 记录变更
    const change: DispatchChange = {
      id: `change-${Date.now()}`,
      type: 'reassign',
      taskId: selectedTask.id,
      taskName: selectedTask.name,
      description: changeDescription,
      operator: '系统管理员',
      timestamp: new Date().toISOString(),
      details: { newMachineryId, newDriverId }
    };
    
    const newChanges = [change, ...dispatchChanges];
    setDispatchChanges(newChanges);
    localStorage.setItem('smart_agriculture_dispatch_changes', JSON.stringify(newChanges));

    // 模拟推送
    toast.success(`任务已重新指派，指令已推送给${updatedTask.driverName}`);
    
    setShowReassignDialog(false);
    setNewMachineryId('keep-current');
    setNewDriverId('keep-current');
    refreshData();
  };

  // 调整优先级
  const handleChangePriority = () => {
    if (!selectedTask || !newPriority) {
      toast.error('请选择新的优先级');
      return;
    }

    const updatedTask = { ...selectedTask, priority: newPriority as any };
    
    const allTasks = JSON.parse(localStorage.getItem('smart_agriculture_tasks') || '[]');
    const updatedTasks = allTasks.map((t: Task) => 
      t.id === updatedTask.id ? updatedTask : t
    );
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(updatedTasks));

    // 记录变更
    const change: DispatchChange = {
      id: `change-${Date.now()}`,
      type: 'priority',
      taskId: selectedTask.id,
      taskName: selectedTask.name,
      description: `优先级: ${getPriorityText(selectedTask.priority)} → ${getPriorityText(newPriority as any)}`,
      operator: '系统管理员',
      timestamp: new Date().toISOString(),
      details: { oldPriority: selectedTask.priority, newPriority }
    };
    
    const newChanges = [change, ...dispatchChanges];
    setDispatchChanges(newChanges);
    localStorage.setItem('smart_agriculture_dispatch_changes', JSON.stringify(newChanges));

    toast.success('优先级已调整');
    setShowPriorityDialog(false);
    setNewPriority('');
    refreshData();
  };

  // 暂停/恢复任务
  const handleTogglePause = (task: Task) => {
    const newStatus: TaskStatus = task.status === '进行中' ? '已分配' : '进行中';
    const action = task.status === '进行中' ? '暂停' : '恢复';
    
    const allTasks = JSON.parse(localStorage.getItem('smart_agriculture_tasks') || '[]');
    const updatedTasks = allTasks.map((t: Task) => 
      t.id === task.id ? { ...t, status: newStatus } : t
    );
    localStorage.setItem('smart_agriculture_tasks', JSON.stringify(updatedTasks));

    // 记录变更
    const change: DispatchChange = {
      id: `change-${Date.now()}`,
      type: task.status === '进行中' ? 'pause' : 'resume',
      taskId: task.id,
      taskName: task.name,
      description: `${action}任务`,
      operator: '系统管理员',
      timestamp: new Date().toISOString(),
      details: { oldStatus: task.status, newStatus }
    };
    
    const newChanges = [change, ...dispatchChanges];
    setDispatchChanges(newChanges);
    localStorage.setItem('smart_agriculture_dispatch_changes', JSON.stringify(newChanges));

    toast.success(`任务已${action}，指令已推送给驾驶员`);
    refreshData();
  };

  // 解决突发事件
  const handleResolveEvent = (event: EmergencyEvent) => {
    const updatedEvents = emergencyEvents.map(e =>
      e.id === event.id ? { ...e, status: 'resolved' as const, resolution: '已处理' } : e
    );
    setEmergencyEvents(updatedEvents);
    localStorage.setItem('smart_agriculture_emergency_events', JSON.stringify(updatedEvents));
    toast.success('事件已标记为已解决');
  };

  // 辅助函数
  const getStatusColor = (status: TaskStatus) => {
    switch (status) {
      case '进行中': return 'bg-success-muted text-success border-success';
      case '已分配': return 'bg-info-muted text-info border-info';
      default: return 'bg-muted text-muted-foreground border-border';
    }
  };

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

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

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'critical': return 'bg-error-muted text-error border-error';
      case 'high': return 'bg-warning-muted text-warning border-warning';
      case 'medium': return 'bg-warning-muted text-warning border-warning';
      case 'low': return 'bg-info-muted text-info border-info';
      default: return 'bg-muted text-muted-foreground border-border';
    }
  };

  const getEmergencyTitle = (type: string) => {
    switch (type) {
      case 'fault': return '农机故障';
      case 'weather': return '天气变化';
      case 'urgent': return '紧急任务';
      default: return '其他事件';
    }
  };

  const getEmergencyIcon = (type: string) => {
    switch (type) {
      case 'fault': return <Wrench className="w-4 h-4" />;
      case 'weather': return <CloudRain className="w-4 h-4" />;
      case 'urgent': return <Zap className="w-4 h-4" />;
      default: return <AlertTriangle className="w-4 h-4" />;
    }
  };

  return (
    <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>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={refreshData}
            disabled={autoRefresh}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${autoRefresh ? 'animate-spin' : ''}`} />
            {autoRefresh ? '自动刷新' : '手动刷新'}
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowHistoryDialog(true)}
          >
            <Clock className="w-4 h-4 mr-2" />
            变更历史
          </Button>
        </div>
      </div>

      {/* 突发事件警告 */}
      {emergencyEvents.filter(e => e.status === 'pending').length > 0 && (
        <Alert className="bg-error-muted border-error">
          <AlertTriangle className="w-4 h-4 text-error" />
          <AlertDescription className="text-error">
            <div className="flex items-center justify-between">
              <span>
                有 {emergencyEvents.filter(e => e.status === 'pending').length} 个突发事件待处理
              </span>
              <Button
                size="sm"
                variant="destructive"
                onClick={() => setSelectedEvent(emergencyEvents.find(e => e.status === 'pending') || null)}
              >
                立即查看
              </Button>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {/* 主内容区 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 地图区域 */}
        <div className="lg:col-span-2 space-y-4">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>调度地图</h3>
              <Badge variant="secondary" className="bg-success-muted text-success">
                <Activity className="w-3 h-3 mr-1 animate-pulse" />
                实时监控
              </Badge>
            </div>
            
            {/* 地图容器 */}
            <div 
              ref={mapContainerRef}
              className="h-[500px] bg-gradient-to-br from-green-50 to-blue-50 rounded-lg border-2 border-dashed relative"
            >
              {!isMapLoaded && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="text-center">
                    <Activity className="w-12 h-12 mx-auto mb-3 text-success animate-pulse" />
                    <p className="text-sm text-muted-foreground">加载地图中...</p>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {/* 任务列表 */}
          <Card className="p-6">
            <h3 className="mb-4">执行中的任务</h3>
            <div className="space-y-3">
              {tasks.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Activity className="w-12 h-12 mx-auto mb-2 opacity-20" />
                  <p>暂无执行中的任务</p>
                </div>
              ) : (
                tasks.map(task => (
                  <Card
                    key={task.id}
                    className={`p-4 cursor-pointer transition-all hover:shadow-md ${
                      selectedTask?.id === task.id ? 'border-2 border-success bg-success-muted' : ''
                    }`}
                    onClick={() => setSelectedTask(task)}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h4 className="text-sm">{task.name}</h4>
                          <Badge variant="secondary" className={getStatusColor(task.status)}>
                            {task.status}
                          </Badge>
                          <Badge variant="secondary" className={getPriorityColor(task.priority)}>
                            {getPriorityText(task.priority)}
                          </Badge>
                        </div>
                        <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground">
                          <div>
                            <Tractor className="w-3 h-3 inline mr-1" />
                            {task.machineryName}
                          </div>
                          <div>
                            <Users className="w-3 h-3 inline mr-1" />
                            {task.driverName}
                          </div>
                          <div>
                            <MapPin className="w-3 h-3 inline mr-1" />
                            {task.fieldName || '未指定地块'}
                          </div>
                          <div>
                            <Clock className="w-3 h-3 inline mr-1" />
                            {new Date(task.startTime).toLocaleTimeString('zh-CN', {
                              hour: '2-digit',
                              minute: '2-digit'
                            })}
                          </div>
                        </div>
                      </div>
                      <div className="flex gap-1">
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleTogglePause(task);
                          }}
                          title={task.status === '进行中' ? '暂停任务' : '恢复任务'}
                        >
                          {task.status === '进行中' ? (
                            <Pause className="w-4 h-4" />
                          ) : (
                            <Play className="w-4 h-4" />
                          )}
                        </Button>
                      </div>
                    </div>
                  </Card>
                ))
              )}
            </div>
          </Card>
        </div>

        {/* 右侧操作面板 */}
        <div className="space-y-4">
          {/* 选中任务信息 */}
          {selectedTask && (
            <Card className="p-4 bg-success-muted border-success">
              <h4 className="text-muted-foreground mb-2">选中任务</h4>
              <div className="text-sm space-y-1">
                <div className="font-medium">{selectedTask.name}</div>
                <div className="text-muted-foreground">
                  {selectedTask.machineryName} / {selectedTask.driverName}
                </div>
              </div>
            </Card>
          )}

          {/* 快速调度操作 */}
          <Card className="p-4">
            <h3 className="mb-3">调度操作</h3>
            <div className="space-y-2">
              <Button
                className="w-full justify-start"
                variant="outline"
                size="sm"
                disabled={!selectedTask}
                onClick={() => setShowReassignDialog(true)}
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新指派任务
              </Button>
              <Button
                className="w-full justify-start"
                variant="outline"
                size="sm"
                disabled={!selectedTask}
                onClick={() => setShowPriorityDialog(true)}
              >
                <TrendingUp className="w-4 h-4 mr-2" />
                调整优先级
              </Button>
            </div>
          </Card>

          {/* 统计信息 */}
          <Card className="p-4">
            <h3 className="mb-3">实时统计</h3>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">执行中任务</span>
                <Badge variant="secondary" className="bg-success-muted text-success">
                  {tasks.filter(t => t.status === '进行中').length}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">待执行任务</span>
                <Badge variant="secondary" className="bg-info-muted text-info">
                  {tasks.filter(t => t.status === '已分配').length}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">待处理事件</span>
                <Badge variant="secondary" className="bg-warning-muted text-warning">
                  {emergencyEvents.filter(e => e.status === 'pending').length}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">今日调度变更</span>
                <Badge variant="secondary" className="bg-accent-muted text-accent">
                  {dispatchChanges.length}
                </Badge>
              </div>
            </div>
          </Card>

          {/* 突发事件列表 */}
          <Card className="p-4">
            <h3 className="mb-3">突发事件</h3>
            <div className="space-y-2 max-h-[300px] overflow-y-auto">
              {emergencyEvents.filter(e => e.status !== 'resolved').length === 0 ? (
                <div className="text-center py-4 text-sm text-muted-foreground">
                  <CheckCircle2 className="w-8 h-8 mx-auto mb-2 opacity-20" />
                  暂无待处理事件
                </div>
              ) : (
                emergencyEvents
                  .filter(e => e.status !== 'resolved')
                  .map(event => (
                    <div
                      key={event.id}
                      className={`p-3 border rounded-lg cursor-pointer hover:bg-gray-50 ${
                        getSeverityColor(event.severity)
                      }`}
                      onClick={() => setSelectedEvent(event)}
                    >
                      <div className="flex items-start gap-2">
                        {getEmergencyIcon(event.type)}
                        <div className="flex-1 text-xs">
                          <div className="font-medium mb-1">{event.title}</div>
                          <div className="text-muted-foreground">{event.description}</div>
                        </div>
                      </div>
                      {event.status === 'pending' && (
                        <Button
                          size="sm"
                          variant="ghost"
                          className="w-full mt-2"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleResolveEvent(event);
                          }}
                        >
                          <CheckCircle2 className="w-3 h-3 mr-1" />
                          标记已解决
                        </Button>
                      )}
                    </div>
                  ))
              )}
            </div>
          </Card>
        </div>
      </div>

      {/* 重新指派对话框 */}
      <Dialog open={showReassignDialog} onOpenChange={setShowReassignDialog}>
        <DialogContent aria-describedby="reassign-dialog-description">
          <DialogHeader>
            <DialogTitle>重新指派任务</DialogTitle>
            <DialogDescription id="reassign-dialog-description">
              为任务 "{selectedTask?.name}" 重新分配农机或驾驶员
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {selectedTask && (
              <div className="p-3 bg-gray-50 rounded-lg text-sm">
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <span className="text-muted-foreground">当前农机:</span>
                    <div className="font-medium">{selectedTask.machineryName}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">当前驾驶员:</span>
                    <div className="font-medium">{selectedTask.driverName}</div>
                  </div>
                </div>
              </div>
            )}

            <div>
              <Label>更换农机（可选）</Label>
              <Select value={newMachineryId} onValueChange={setNewMachineryId}>
                <SelectTrigger>
                  <SelectValue placeholder="保持不变" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="keep-current">保持不变</SelectItem>
                  {machinery
                    .filter(m => m.id !== selectedTask?.machineryId)
                    .map(m => (
                      <SelectItem key={m.id} value={m.id}>
                        {m.name} - {m.type}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>更换驾驶员（可选）</Label>
              <Select value={newDriverId} onValueChange={setNewDriverId}>
                <SelectTrigger>
                  <SelectValue placeholder="保持不变" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="keep-current">保持不变</SelectItem>
                  {drivers
                    .filter(d => d.id !== selectedTask?.driverId)
                    .map(d => (
                      <SelectItem key={d.id} value={d.id}>
                        {d.name} - {d.phone}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>

            <Alert>
              <Bell className="w-4 h-4" />
              <AlertDescription className="text-sm">
                重新指派后将立即推送新指令给驾驶员
              </AlertDescription>
            </Alert>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowReassignDialog(false)}>
              取消
            </Button>
            <Button onClick={handleReassignTask}>
              <CheckCircle2 className="w-4 h-4 mr-2" />
              确认指派并推送
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 调整优先级对话框 */}
      <Dialog open={showPriorityDialog} onOpenChange={setShowPriorityDialog}>
        <DialogContent aria-describedby="priority-dialog-description">
          <DialogHeader>
            <DialogTitle>调整任务优先级</DialogTitle>
            <DialogDescription id="priority-dialog-description">
              调整任务 "{selectedTask?.name}" 的优先级
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {selectedTask && (
              <div className="p-3 bg-gray-50 rounded-lg text-sm">
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">当前优先级:</span>
                  <Badge className={getPriorityColor(selectedTask.priority)}>
                    {getPriorityText(selectedTask.priority)}
                  </Badge>
                </div>
              </div>
            )}

            <div>
              <Label>新优先级</Label>
              <Select value={newPriority} onValueChange={setNewPriority}>
                <SelectTrigger>
                  <SelectValue placeholder="选择优先级" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="urgent">紧急</SelectItem>
                  <SelectItem value="high">高</SelectItem>
                  <SelectItem value="medium">中</SelectItem>
                  <SelectItem value="low">低</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPriorityDialog(false)}>
              取消
            </Button>
            <Button onClick={handleChangePriority}>
              确认调整
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 变更历史对话框 */}
      <Dialog open={showHistoryDialog} onOpenChange={setShowHistoryDialog}>
        <DialogContent className="max-w-3xl" aria-describedby="history-dialog-description">
          <DialogHeader>
            <DialogTitle>调度变更历史</DialogTitle>
            <DialogDescription id="history-dialog-description">
              查看所有调度方案的变更记录
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 max-h-[500px] overflow-y-auto">
            {dispatchChanges.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Clock className="w-12 h-12 mx-auto mb-2 opacity-20" />
                <p>暂无变更记录</p>
              </div>
            ) : (
              dispatchChanges.map(change => (
                <div key={change.id} className="p-4 border rounded-lg">
                  <div className="flex items-start gap-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant="secondary">
                          {change.type === 'reassign' && '重新指派'}
                          {change.type === 'priority' && '优先级调整'}
                          {change.type === 'pause' && '暂停任务'}
                          {change.type === 'resume' && '恢复任务'}
                          {change.type === 'emergency' && '突发事件'}
                        </Badge>
                        <span className="text-sm text-muted-foreground">
                          {new Date(change.timestamp).toLocaleString('zh-CN')}
                        </span>
                      </div>
                      <div className="text-sm mb-1">
                        <span className="font-medium">{change.taskName}</span>
                      </div>
                      <div className="text-sm text-muted-foreground">
                        {change.description}
                      </div>
                      <div className="text-xs text-muted-foreground mt-1">
                        操作人: {change.operator}
                      </div>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

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

      {/* 事件详情对话框 */}
      {selectedEvent && (
        <Dialog open={!!selectedEvent} onOpenChange={() => setSelectedEvent(null)}>
          <DialogContent aria-describedby="event-detail-description">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                {getEmergencyIcon(selectedEvent.type)}
                {selectedEvent.title}
              </DialogTitle>
              <DialogDescription id="event-detail-description">
                查看突发事件的详细信息和处理状态
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">严重程度:</span>
                  <Badge className={getSeverityColor(selectedEvent.severity)}>
                    {selectedEvent.severity}
                  </Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">发生时间:</span>
                  <span>{new Date(selectedEvent.timestamp).toLocaleString('zh-CN')}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">状态:</span>
                  <Badge>
                    {selectedEvent.status === 'pending' && '待处理'}
                    {selectedEvent.status === 'handling' && '处理中'}
                    {selectedEvent.status === 'resolved' && '已解决'}
                  </Badge>
                </div>
              </div>

              <div>
                <Label>事件描述</Label>
                <p className="mt-2 text-sm text-muted-foreground">
                  {selectedEvent.description}
                </p>
              </div>

              {selectedEvent.status === 'pending' && (
                <Alert className="bg-warning-muted border-warning">
                  <AlertTriangle className="w-4 h-4 text-warning" />
                  <AlertDescription className="text-sm text-warning">
                    请及时处理此事件，避免影响作业进度
                  </AlertDescription>
                </Alert>
              )}
            </div>

            <DialogFooter>
              {selectedEvent.status === 'pending' && (
                <Button
                  variant="default"
                  onClick={() => {
                    handleResolveEvent(selectedEvent);
                    setSelectedEvent(null);
                  }}
                >
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  标记已解决
                </Button>
              )}
              <Button variant="outline" onClick={() => setSelectedEvent(null)}>
                关闭
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
