import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Textarea } from '../../ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { 
  Send, CheckCircle, Clock, XCircle, AlertTriangle, RefreshCw, 
  Eye, Download, FileText, Radio, MapPin, Settings, Zap
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { usePagination } from '../../../lib/usePagination';
import { DataPagination } from '../../ui/data-pagination';

// 下发指令状态
type DispatchStatus = '待发送' | '已发送' | '已接收' | '已执行' | '执行失败' | '超时';

// 通信协议类型
type Protocol = 'MQTT' | 'HTTP' | 'WebSocket' | 'TCP';

// 下发记录
interface DispatchRecord {
  id: string;
  dispatchNumber: string;
  machineryId: string;
  machineryName: string;
  driverId?: string;
  driverName?: string;
  routePlanId?: string;
  routePlanName?: string;
  taskType: string;
  description: string;
  plannedStartTime?: string;  // 计划开始时间
  parameters: {
    targetSpeed?: number;      // 目标速率 km/h
    workingWidth?: number;      // 作业幅宽 m
    workingDepth?: number;      // 作业深度 cm
    rowSpacing?: number;        // 行距 m
    seedingRate?: number;       // 播种量 kg/亩
    fertilizerRate?: number;    // 施肥量 kg/亩
    customParams?: Record<string, any>;  // 自定义参数
  };
  protocol: Protocol;
  status: DispatchStatus;
  dispatchedAt: string;
  receivedAt?: string;
  executedAt?: string;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
  priority: 'urgent' | 'high' | 'medium' | 'low';
  dispatchedBy: string;
  deviceStatus?: 'online' | 'offline' | 'unknown';
  signalStrength?: number;  // 信号强度 0-100
}

export function PlanDispatch() {
  const [dispatches, setDispatches] = useState<DispatchRecord[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [routes, setRoutes] = useState<any[]>([]);
  const [drivers, setDrivers] = useState<any[]>([]);
  const [showDispatchDialog, setShowDispatchDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedDispatch, setSelectedDispatch] = useState<DispatchRecord | null>(null);
  const [selectedMachinery, setSelectedMachinery] = useState<string>('');
  const [selectedRoute, setSelectedRoute] = useState<string>('none');
  const [selectedDriver, setSelectedDriver] = useState<string>('none');
  const [taskType, setTaskType] = useState<string>('');
  const [description, setDescription] = useState<string>('');
  const [plannedStartTime, setPlannedStartTime] = useState<string>('');
  const [protocol, setProtocol] = useState<Protocol>('MQTT');
  const [priority, setPriority] = useState<'urgent' | 'high' | 'medium' | 'low'>('medium');
  const [parameters, setParameters] = useState({
    targetSpeed: 5,
    workingWidth: 2.5,
    workingDepth: 25,
    rowSpacing: 3,
  });

  useEffect(() => {
    loadData();

    // 模拟实时状态更新
    const interval = setInterval(() => {
      updateDeviceStatus();
    }, 5000);

    return () => clearInterval(interval);
  }, []);

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

    // 加载路线规划
    const routesData = localStorage.getItem('smart_agriculture_route_plans');
    if (routesData) {
      setRoutes(JSON.parse(routesData));
    }

    // 加载司机
    const driversData = localStorage.getItem('smart_agriculture_drivers');
    if (driversData) {
      setDrivers(JSON.parse(driversData));
    }

    // 加载下发记录
    const dispatchesData = localStorage.getItem('smart_agriculture_dispatches');
    if (dispatchesData) {
      setDispatches(JSON.parse(dispatchesData));
    } else {
      // 初始化示例数据
      const mockDispatches: DispatchRecord[] = [
        {
          id: 'dispatch-1',
          dispatchNumber: 'D20251017001',
          machineryId: machineryData[0]?.id || 'machinery-1',
          machineryName: machineryData[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-1',
          driverName: '张三',
          routePlanId: 'route-1',
          routePlanName: '东地1号作业路线',
          taskType: '耕地',
          description: '深耕作业，准备春播',
          plannedStartTime: '2025-10-18T08:00:00',
          parameters: {
            targetSpeed: 5,
            workingWidth: 2.5,
            workingDepth: 25,
          },
          protocol: 'MQTT',
          status: '已执行',
          dispatchedAt: '2025-10-17T08:00:00',
          receivedAt: '2025-10-17T08:01:30',
          executedAt: '2025-10-17T08:05:00',
          retryCount: 0,
          maxRetries: 3,
          priority: 'high',
          dispatchedBy: '系统管理员',
          deviceStatus: 'online',
          signalStrength: 85,
        },
        {
          id: 'dispatch-2',
          dispatchNumber: 'D20251017002',
          machineryId: machineryData[1]?.id || 'machinery-2',
          machineryName: machineryData[1]?.name || '久保田播种机',
          driverId: 'driver-2',
          driverName: '李四',
          routePlanId: 'route-2',
          routePlanName: '西地2号作业路线',
          taskType: '播种',
          description: '玉米播种作业',
          plannedStartTime: '2025-10-18T09:30:00',
          parameters: {
            targetSpeed: 4,
            workingWidth: 3,
            rowSpacing: 0.6,
            seedingRate: 2.5,
          },
          protocol: 'MQTT',
          status: '已接收',
          dispatchedAt: '2025-10-17T09:00:00',
          receivedAt: '2025-10-17T09:02:15',
          retryCount: 0,
          maxRetries: 3,
          priority: 'medium',
          dispatchedBy: '系统管理员',
          deviceStatus: 'online',
          signalStrength: 92,
        },
        {
          id: 'dispatch-3',
          dispatchNumber: 'D20251017003',
          machineryId: machineryData[2]?.id || 'machinery-3',
          machineryName: machineryData[2]?.name || '雷沃施肥机',
          driverId: 'driver-3',
          driverName: '王五',
          taskType: '施肥',
          description: '追肥作业',
          parameters: {
            targetSpeed: 6,
            workingWidth: 4,
            fertilizerRate: 30,
          },
          protocol: 'MQTT',
          status: '已发送',
          dispatchedAt: '2025-10-17T10:30:00',
          retryCount: 0,
          maxRetries: 3,
          priority: 'medium',
          dispatchedBy: '系统管理员',
          deviceStatus: 'online',
          signalStrength: 78,
        },
        {
          id: 'dispatch-4',
          dispatchNumber: 'D20251017004',
          machineryId: machineryData[0]?.id || 'machinery-1',
          machineryName: machineryData[0]?.name || '约翰迪尔拖拉机',
          driverId: 'driver-1',
          driverName: '张三',
          taskType: '耙地',
          description: '整地作业',
          parameters: {
            targetSpeed: 5.5,
            workingWidth: 2.8,
            workingDepth: 15,
          },
          protocol: 'MQTT',
          status: '执行失败',
          dispatchedAt: '2025-10-17T07:00:00',
          receivedAt: '2025-10-17T07:01:00',
          failureReason: '设备传感器故障，无法读取作业深度',
          retryCount: 2,
          maxRetries: 3,
          priority: 'low',
          dispatchedBy: '系统管理员',
          deviceStatus: 'online',
          signalStrength: 85,
        },
      ];
      localStorage.setItem('smart_agriculture_dispatches', JSON.stringify(mockDispatches));
      setDispatches(mockDispatches);
    }
  };

  // 模拟设备状态更新
  const updateDeviceStatus = () => {
    setDispatches(prev => prev.map(d => {
      // 模拟状态变化
      if (d.status === '已发送' && Math.random() > 0.5) {
        return {
          ...d,
          status: '已接收' as DispatchStatus,
          receivedAt: new Date().toISOString(),
          signalStrength: 75 + Math.random() * 25,
        };
      }
      if (d.status === '已接收' && Math.random() > 0.7) {
        return {
          ...d,
          status: '已执行' as DispatchStatus,
          executedAt: new Date().toISOString(),
        };
      }
      return {
        ...d,
        signalStrength: d.signalStrength ? Math.max(50, Math.min(100, d.signalStrength + (Math.random() - 0.5) * 10)) : undefined,
      };
    }));
  };

  const handleDispatch = () => {
    if (!selectedMachinery || !taskType) {
      toast.error('请选择农机和任务类型');
      return;
    }

    const selectedMachineryData = machinery.find(m => m.id === selectedMachinery);
    const selectedRouteData = selectedRoute && selectedRoute !== 'none' 
      ? routes.find(r => r.id === selectedRoute) 
      : null;
    const selectedDriverData = selectedDriver && selectedDriver !== 'none'
      ? drivers.find(d => d.id === selectedDriver)
      : null;

    const newDispatch: DispatchRecord = {
      id: `dispatch-${Date.now()}`,
      dispatchNumber: `D${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(dispatches.length + 1).padStart(3, '0')}`,
      machineryId: selectedMachinery,
      machineryName: selectedMachineryData?.name || '',
      driverId: selectedDriverData?.id,
      driverName: selectedDriverData?.name,
      routePlanId: selectedRoute && selectedRoute !== 'none' ? selectedRoute : undefined,
      routePlanName: selectedRouteData?.name || undefined,
      taskType,
      description,
      plannedStartTime: plannedStartTime || undefined,
      parameters,
      protocol,
      status: '待发送',
      dispatchedAt: new Date().toISOString(),
      retryCount: 0,
      maxRetries: 3,
      priority,
      dispatchedBy: '系统管理员',
      deviceStatus: 'online',
      signalStrength: 80 + Math.random() * 20,
    };

    // 模拟发送过程
    setTimeout(() => {
      newDispatch.status = '已发送';
      const newDispatches = [...dispatches, newDispatch];
      setDispatches(newDispatches);
      localStorage.setItem('smart_agriculture_dispatches', JSON.stringify(newDispatches));
      toast.success(`方案已下发至${newDispatch.machineryName}`);
      setShowDispatchDialog(false);
      resetForm();
    }, 500);

    toast.info('正在下发作业方案...');
  };

  const handleRetry = (id: string) => {
    const updatedDispatches = dispatches.map(d => {
      if (d.id === id && d.retryCount < d.maxRetries) {
        toast.info('正在重新下发...');
        setTimeout(() => {
          toast.success('重新下发成功');
        }, 1000);
        return {
          ...d,
          status: '已发送' as DispatchStatus,
          retryCount: d.retryCount + 1,
          dispatchedAt: new Date().toISOString(),
        };
      }
      return d;
    });
    setDispatches(updatedDispatches);
    localStorage.setItem('smart_agriculture_dispatches', JSON.stringify(updatedDispatches));
  };

  const resetForm = () => {
    setSelectedMachinery('');
    setSelectedRoute('none');
    setSelectedDriver('none');
    setTaskType('');
    setDescription('');
    setPlannedStartTime('');
    setProtocol('MQTT');
    setPriority('medium');
    setParameters({
      targetSpeed: 5,
      workingWidth: 2.5,
      workingDepth: 25,
      rowSpacing: 3,
    });
  };

  const getStatusColor = (status: DispatchStatus) => {
    switch (status) {
      case '已执行': return 'bg-success-muted text-success';
      case '已接收': return 'bg-info-muted text-info';
      case '已发送': return 'bg-warning-muted text-warning';
      case '待发送': return 'bg-muted text-muted-foreground';
      case '执行失败': return 'bg-error-muted text-error';
      case '超时': return 'bg-warning-muted text-warning';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusIcon = (status: DispatchStatus) => {
    switch (status) {
      case '已执行': return CheckCircle;
      case '已接收': return CheckCircle;
      case '已发送': return Clock;
      case '待发送': return Clock;
      case '执行失败': return XCircle;
      case '超时': return AlertTriangle;
      default: return Clock;
    }
  };

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

  const getDeviceStatusBadge = (status?: string, signalStrength?: number) => {
    if (status === 'online') {
      return (
        <div className="flex items-center gap-1">
          <span className="inline-block w-2 h-2 bg-success rounded-full animate-pulse"></span>
          <span className="text-xs text-success">在线</span>
          {signalStrength && (
            <span className="text-xs text-muted-foreground">({signalStrength.toFixed(0)}%)</span>
          )}
        </div>
      );
    } else if (status === 'offline') {
      return (
        <div className="flex items-center gap-1">
          <span className="inline-block w-2 h-2 bg-gray-400 rounded-full"></span>
          <span className="text-xs text-gray-600">离线</span>
        </div>
      );
    }
    return <span className="text-xs text-muted-foreground">未知</span>;
  };

  // 统计
  const stats = {
    total: dispatches.length,
    pending: dispatches.filter(d => d.status === '待发送').length,
    sent: dispatches.filter(d => d.status === '已发送').length,
    received: dispatches.filter(d => d.status === '已接收').length,
    executed: dispatches.filter(d => d.status === '已执行').length,
    failed: dispatches.filter(d => d.status === '执行失败' || d.status === '超时').length,
    online: dispatches.filter(d => d.deviceStatus === 'online').length,
  };

  const pagination = usePagination(dispatches, 10);

  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>
        <Button onClick={() => setShowDispatchDialog(true)}>
          <Send className="w-4 h-4 mr-2" />
          新建下发
        </Button>
      </div>

      {/* 统计 */}
      <div className="grid grid-cols-2 md:grid-cols-7 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总下发数</div>
          <div className="mt-1">{stats.total}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待发送</div>
          <div className="mt-1 text-gray-600">{stats.pending}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已发送</div>
          <div className="mt-1 text-warning">{stats.sent}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已接收</div>
          <div className="mt-1 text-info">{stats.received}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已执行</div>
          <div className="mt-1 text-success">{stats.executed}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">失败/超时</div>
          <div className="mt-1 text-error">{stats.failed}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">设备在线</div>
          <div className="mt-1 text-success">{stats.online}</div>
        </Card>
      </div>

      {/* 下发记录 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>下发编号</TableHead>
              <TableHead>农机</TableHead>
              <TableHead>任���类型</TableHead>
              <TableHead>路线方案</TableHead>
              <TableHead>优先级</TableHead>
              <TableHead>协议</TableHead>
              <TableHead>设备状态</TableHead>
              <TableHead>下发时间</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {pagination.paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={10} className="text-center text-muted-foreground py-8">
                  暂无下发记录
                </TableCell>
              </TableRow>
            ) : (
              pagination.paginatedData.map(dispatch => {
                const StatusIcon = getStatusIcon(dispatch.status);
                
                return (
                  <TableRow key={dispatch.id}>
                    <TableCell className="font-mono text-xs">{dispatch.dispatchNumber}</TableCell>
                    <TableCell>{dispatch.machineryName}</TableCell>
                    <TableCell>{dispatch.taskType}</TableCell>
                    <TableCell>
                      {dispatch.routePlanName || <span className="text-muted-foreground">-</span>}
                    </TableCell>
                    <TableCell>
                      <span className={getPriorityColor(dispatch.priority)}>
                        {dispatch.priority === 'urgent' ? '紧急' : 
                         dispatch.priority === 'high' ? '高' : 
                         dispatch.priority === 'medium' ? '中' : '低'}
                      </span>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{dispatch.protocol}</Badge>
                    </TableCell>
                    <TableCell>
                      {getDeviceStatusBadge(dispatch.deviceStatus, dispatch.signalStrength)}
                    </TableCell>
                    <TableCell className="text-xs">
                      {new Date(dispatch.dispatchedAt).toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={getStatusColor(dispatch.status)}>
                        <StatusIcon className="w-3 h-3 mr-1" />
                        {dispatch.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedDispatch(dispatch);
                            setShowDetailDialog(true);
                          }}
                          title="查看详情"
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                        {(dispatch.status === '执行失败' || dispatch.status === '超时') && 
                         dispatch.retryCount < dispatch.maxRetries && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRetry(dispatch.id)}
                            title="重新下发"
                          >
                            <RefreshCw className="w-4 h-4" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
        
        <div className="p-4 border-t">
          <DataPagination
            currentPage={pagination.currentPage}
            totalPages={pagination.totalPages}
            pageSize={pagination.pageSize}
            totalItems={pagination.totalItems}
            onPageChange={pagination.goToPage}
            onPageSizeChange={pagination.changePageSize}
          />
        </div>
      </Card>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">🎯 智能下发系统</h4>
        <div className="grid md:grid-cols-3 gap-4 text-sm text-muted-foreground">
          <div>
            <h5 className="mb-2">📡 通信协议</h5>
            <ul className="space-y-1">
              <li>• MQTT - 物联网标准协议</li>
              <li>• HTTP - 通用Web协议</li>
              <li>• WebSocket - 双向通信</li>
              <li>• TCP - 可靠传输</li>
            </ul>
          </div>
          <div>
            <h5 className="mb-2">📊 状态跟踪</h5>
            <ul className="space-y-1">
              <li>• 待发送 → 准备中</li>
              <li>• 已发送 → 传输中</li>
              <li>• 已接收 → 机手确认</li>
              <li>• 已执行 → 开始作业</li>
            </ul>
          </div>
          <div>
            <h5 className="mb-2">🔐 安全保障</h5>
            <ul className="space-y-1">
              <li>• 指令加密传输</li>
              <li>• 设备身份认证</li>
              <li>• 失败自动重试</li>
              <li>• 实时状态监控</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 下发对话框 */}
      <Dialog open={showDispatchDialog} onOpenChange={setShowDispatchDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>新建作业方案下发</DialogTitle>
            <DialogDescription>
              选择农机和作业参数，一键下发至终端设备
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>农机设备 *</Label>
                <Select value={selectedMachinery} onValueChange={setSelectedMachinery}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择农机" />
                  </SelectTrigger>
                  <SelectContent>
                    {machinery.map(m => (
                      <SelectItem key={m.id} value={m.id}>
                        {m.name} ({m.model})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>司机</Label>
                <Select value={selectedDriver} onValueChange={setSelectedDriver}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择司机（可选）" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不选择司机</SelectItem>
                    {drivers.filter(d => d.status === '在岗').map(d => (
                      <SelectItem key={d.id} value={d.id}>
                        {d.name} ({d.driverLicense?.licenseNumber || '无驾照'})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>路线方案</Label>
                <Select value={selectedRoute} onValueChange={setSelectedRoute}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择路线（可选）" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">不选择路线</SelectItem>
                    {routes.map(r => (
                      <SelectItem key={r.id} value={r.id}>
                        {r.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>任务类型 *</Label>
                <Select value={taskType} onValueChange={setTaskType}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择任务类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="耕地">耕地</SelectItem>
                    <SelectItem value="播种">播种</SelectItem>
                    <SelectItem value="施肥">施肥</SelectItem>
                    <SelectItem value="喷药">喷药</SelectItem>
                    <SelectItem value="收获">收获</SelectItem>
                    <SelectItem value="灌溉">灌溉</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>优先级</Label>
                <Select value={priority} onValueChange={(v: any) => setPriority(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="urgent">紧急</SelectItem>
                    <SelectItem value="high">高</SelectItem>
                    <SelectItem value="medium">中</SelectItem>
                    <SelectItem value="low">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>通信协议</Label>
                <Select value={protocol} onValueChange={(v: any) => setProtocol(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="MQTT">MQTT</SelectItem>
                    <SelectItem value="HTTP">HTTP</SelectItem>
                    <SelectItem value="WebSocket">WebSocket</SelectItem>
                    <SelectItem value="TCP">TCP</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>任务描述</Label>
              <Textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="输入任务描述..."
                rows={2}
              />
            </div>

            <div>
              <Label>计划开始时间</Label>
              <Input
                type="datetime-local"
                value={plannedStartTime}
                onChange={(e) => setPlannedStartTime(e.target.value)}
                placeholder="选择计划开始时间（可选）"
              />
            </div>

            <div className="border-t pt-4">
              <h4 className="text-sm mb-3">作业参数</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>目标速率 (km/h)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={parameters.targetSpeed}
                    onChange={(e) => setParameters({
                      ...parameters,
                      targetSpeed: Number(e.target.value)
                    })}
                  />
                </div>
                <div>
                  <Label>作业幅宽 (m)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={parameters.workingWidth}
                    onChange={(e) => setParameters({
                      ...parameters,
                      workingWidth: Number(e.target.value)
                    })}
                  />
                </div>
                <div>
                  <Label>作业深度 (cm)</Label>
                  <Input
                    type="number"
                    value={parameters.workingDepth}
                    onChange={(e) => setParameters({
                      ...parameters,
                      workingDepth: Number(e.target.value)
                    })}
                  />
                </div>
                <div>
                  <Label>行距 (m)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={parameters.rowSpacing}
                    onChange={(e) => setParameters({
                      ...parameters,
                      rowSpacing: Number(e.target.value)
                    })}
                  />
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h4 className="text-sm mb-3">通信设置</h4>
              <div>
                <Label>通信协议</Label>
                <Select value={protocol} onValueChange={(v: Protocol) => setProtocol(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="MQTT">MQTT (推荐)</SelectItem>
                    <SelectItem value="HTTP">HTTP</SelectItem>
                    <SelectItem value="WebSocket">WebSocket</SelectItem>
                    <SelectItem value="TCP">TCP</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground mt-1">
                  {protocol === 'MQTT' && '物联网标准协议，低功耗，适合移动设备'}
                  {protocol === 'HTTP' && '通用Web协议，兼容性好'}
                  {protocol === 'WebSocket' && '双向实时通信，低延迟'}
                  {protocol === 'TCP' && '可靠传输，适合大数据量'}
                </p>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowDispatchDialog(false);
              resetForm();
            }}>
              取消
            </Button>
            <Button onClick={handleDispatch}>
              <Send className="w-4 h-4 mr-2" />
              立即下发
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>下发详情</DialogTitle>
            <DialogDescription>
              下发编号: {selectedDispatch?.dispatchNumber}
            </DialogDescription>
          </DialogHeader>

          {selectedDispatch && (
            <div className="space-y-4 py-4">
              {/* 基本信息 */}
              <Card className="p-4">
                <h4 className="text-sm mb-3">基本信息</h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">农机设备:</span>
                    <span className="ml-2">{selectedDispatch.machineryName}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">任务类型:</span>
                    <span className="ml-2">{selectedDispatch.taskType}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">路线方案:</span>
                    <span className="ml-2">{selectedDispatch.routePlanName || '未关联'}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">优先级:</span>
                    <span className={`ml-2 ${getPriorityColor(selectedDispatch.priority)}`}>
                      {selectedDispatch.priority === 'urgent' ? '紧急' : 
                       selectedDispatch.priority === 'high' ? '高' : 
                       selectedDispatch.priority === 'medium' ? '中' : '低'}
                    </span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">计划开始时间:</span>
                    <span className="ml-2">
                      {selectedDispatch.plannedStartTime ? 
                        new Date(selectedDispatch.plannedStartTime).toLocaleString('zh-CN', {
                          year: 'numeric',
                          month: '2-digit',
                          day: '2-digit',
                          hour: '2-digit',
                          minute: '2-digit'
                        }) : 
                        <span className="text-muted-foreground">-</span>
                      }
                    </span>
                  </div>
                  <div className="col-span-2">
                    <span className="text-muted-foreground">任务描述:</span>
                    <span className="ml-2">{selectedDispatch.description}</span>
                  </div>
                </div>
              </Card>

              {/* 作业参数 */}
              <Card className="p-4">
                <h4 className="text-sm mb-3">作业参数</h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  {selectedDispatch.parameters.targetSpeed && (
                    <div>
                      <span className="text-muted-foreground">目标速率:</span>
                      <span className="ml-2">{selectedDispatch.parameters.targetSpeed} km/h</span>
                    </div>
                  )}
                  {selectedDispatch.parameters.workingWidth && (
                    <div>
                      <span className="text-muted-foreground">作业幅宽:</span>
                      <span className="ml-2">{selectedDispatch.parameters.workingWidth} m</span>
                    </div>
                  )}
                  {selectedDispatch.parameters.workingDepth && (
                    <div>
                      <span className="text-muted-foreground">作业深度:</span>
                      <span className="ml-2">{selectedDispatch.parameters.workingDepth} cm</span>
                    </div>
                  )}
                  {selectedDispatch.parameters.rowSpacing && (
                    <div>
                      <span className="text-muted-foreground">行距:</span>
                      <span className="ml-2">{selectedDispatch.parameters.rowSpacing} m</span>
                    </div>
                  )}
                </div>
              </Card>

              {/* 通信信息 */}
              <Card className="p-4">
                <h4 className="text-sm mb-3">通信信息</h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">通信协议:</span>
                    <Badge variant="outline" className="ml-2">{selectedDispatch.protocol}</Badge>
                  </div>
                  <div>
                    <span className="text-muted-foreground">设备状态:</span>
                    <span className="ml-2">
                      {getDeviceStatusBadge(selectedDispatch.deviceStatus, selectedDispatch.signalStrength)}
                    </span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">重试次数:</span>
                    <span className="ml-2">{selectedDispatch.retryCount} / {selectedDispatch.maxRetries}</span>
                  </div>
                </div>
              </Card>

              {/* 状态跟踪 */}
              <Card className="p-4">
                <h4 className="text-sm mb-3">状态跟踪</h4>
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <div className="w-24 text-sm text-muted-foreground">下发时间:</div>
                    <div className="text-sm">
                      {new Date(selectedDispatch.dispatchedAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                  {selectedDispatch.receivedAt && (
                    <div className="flex items-center gap-3">
                      <div className="w-24 text-sm text-muted-foreground">接收时间:</div>
                      <div className="text-sm">
                        {new Date(selectedDispatch.receivedAt).toLocaleString('zh-CN')}
                      </div>
                    </div>
                  )}
                  {selectedDispatch.executedAt && (
                    <div className="flex items-center gap-3">
                      <div className="w-24 text-sm text-muted-foreground">执行时间:</div>
                      <div className="text-sm">
                        {new Date(selectedDispatch.executedAt).toLocaleString('zh-CN')}
                      </div>
                    </div>
                  )}
                  {selectedDispatch.failureReason && (
                    <div className="flex items-start gap-3">
                      <div className="w-24 text-sm text-muted-foreground">失败原因:</div>
                      <div className="text-sm text-error">
                        {selectedDispatch.failureReason}
                      </div>
                    </div>
                  )}
                  <div className="flex items-center gap-3">
                    <div className="w-24 text-sm text-muted-foreground">当前状态:</div>
                    <Badge variant="secondary" className={getStatusColor(selectedDispatch.status)}>
                      {selectedDispatch.status}
                    </Badge>
                  </div>
                </div>
              </Card>
            </div>
          )}

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