import { useState, useEffect } from 'react';
import { AIDeviceControl } from '../ai/AIDeviceControl';
import { AIExternalIntegration } from '../ai/AIExternalIntegration';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import {
  Radio,
  Plug,
  Plus,
  Search,
  Download,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  Settings,
  Eye,
  Edit,
  Trash2,
  Clock,
  Activity,
  Zap,
  BarChart3,
  TrendingUp,
  Wifi,
  WifiOff,
  Power,
  PowerOff,
  Wind,
  Droplets,
  Thermometer,
  Sun,
  Fan,
  Link,
  LinkOff,
  Code,
  Server,
  Database,
  Globe,
  Send,
  History,
  ArrowRight,
  CheckCircle2,
  AlertTriangle,
  Info,
  Copy,
  FileText,
  Terminal,
  Key,
  Shield,
  Webhook,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  AreaChart,
  Area,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AIDecisionApplicationProps {
  activePath?: string;
}

type DeviceType = '灌溉控制器' | '卷帘控制器' | '风机控制器' | '温控系统' | '补光灯' | '其他';
type DeviceStatus = '在线' | '离线' | '故障';
type CommandStatus = '待发送' | '已发送' | '执行中' | '已完成' | '失败';
type APIStatus = '正常' | '异常' | '维护中';
type SystemType = '农事管理系统' | '灌溉控制系统' | '预警推送系统' | '数据分析平台' | '第三方ERP';

interface Device {
  id: string;
  deviceNo: string;
  deviceName: string;
  deviceType: DeviceType;
  location: string;
  ipAddress: string;
  status: DeviceStatus;
  lastOnlineTime: string;
  firmware: string;
  supportCommands: string[];
  executedCount: number;
  successRate: number;
}

interface ControlCommand {
  id: string;
  commandNo: string;
  decisionNo: string;
  deviceName: string;
  deviceType: DeviceType;
  commandType: string;
  commandContent: string;
  parameters: Record<string, any>;
  status: CommandStatus;
  createTime: string;
  sendTime?: string;
  completeTime?: string;
  executionTime?: number;
  feedback?: string;
  errorMessage?: string;
}

interface ExternalSystem {
  id: string;
  systemName: string;
  systemType: SystemType;
  apiEndpoint: string;
  authType: string;
  status: APIStatus;
  lastCallTime?: string;
  totalCalls: number;
  successRate: number;
  avgResponseTime: number;
}

interface APICall {
  id: string;
  callNo: string;
  systemName: string;
  decisionNo: string;
  decisionType: string;
  apiEndpoint: string;
  method: string;
  requestBody: any;
  responseStatus: number;
  responseBody?: any;
  callTime: string;
  responseTime: number;
  success: boolean;
  errorMessage?: string;
}

export function AIDecisionApplication({ activePath }: AIDecisionApplicationProps) {
  // 如果是设备控制集成路径，直接返回设备控制组件
  if (activePath && activePath.includes('/application/device-control')) {
    return <AIDeviceControl activePath={activePath} />;
  }

  // 如果是外部系统联动路径，直接返回外部系统联动组件
  if (activePath && activePath.includes('/application/external-system')) {
    return <AIExternalIntegration activePath={activePath} />;
  }

  const [activeTab, setActiveTab] = useState('overview');
  const [showDeviceDialog, setShowDeviceDialog] = useState(false);
  const [showCommandDialog, setShowCommandDialog] = useState(false);
  const [showSystemDialog, setShowSystemDialog] = useState(false);
  const [showAPITestDialog, setShowAPITestDialog] = useState(false);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const [selectedCommand, setSelectedCommand] = useState<ControlCommand | null>(null);
  const [selectedSystem, setSelectedSystem] = useState<ExternalSystem | null>(null);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/application/external-system')) {
        setActiveTab('external-system');
      }
    }
  }, [activePath]);

  // 设备数据
  const [devices] = useState<Device[]>([
    {
      id: 'dev-1',
      deviceNo: 'DEV-IRT-001',
      deviceName: '1号大棚灌溉控制器',
      deviceType: '灌溉控制器',
      location: '1号大棚',
      ipAddress: '192.168.1.101',
      status: '在线',
      lastOnlineTime: '2024-10-15 18:30:00',
      firmware: 'v2.3.5',
      supportCommands: ['开启灌溉', '关闭灌溉', '设置流量', '查询状态'],
      executedCount: 856,
      successRate: 99.2,
    },
    {
      id: 'dev-2',
      deviceNo: 'DEV-CUR-002',
      deviceName: '2号大棚卷帘控制器',
      deviceType: '卷帘控制器',
      location: '2号大棚',
      ipAddress: '192.168.1.102',
      status: '在线',
      lastOnlineTime: '2024-10-15 18:28:00',
      firmware: 'v1.8.2',
      supportCommands: ['展开卷帘', '收起卷帘', '设置开度', '查询状态'],
      executedCount: 620,
      successRate: 98.5,
    },
    {
      id: 'dev-3',
      deviceNo: 'DEV-FAN-003',
      deviceName: '3号大棚风机控制器',
      deviceType: '风机控制器',
      location: '3号大棚',
      ipAddress: '192.168.1.103',
      status: '在线',
      lastOnlineTime: '2024-10-15 18:25:00',
      firmware: 'v2.1.0',
      supportCommands: ['启动风机', '停止风机', '设置转速', '查询状态'],
      executedCount: 1240,
      successRate: 97.8,
    },
    {
      id: 'dev-4',
      deviceNo: 'DEV-TMP-004',
      deviceName: '4号大棚温控系统',
      deviceType: '温控系统',
      location: '4号大棚',
      ipAddress: '192.168.1.104',
      status: '离线',
      lastOnlineTime: '2024-10-15 16:45:00',
      firmware: 'v3.0.1',
      supportCommands: ['设置温度', '启动加热', '启动制冷', '查询状态'],
      executedCount: 425,
      successRate: 96.5,
    },
  ]);

  // 控制指令数据
  const [controlCommands] = useState<ControlCommand[]>([
    {
      id: 'cmd-1',
      commandNo: 'CMD-20241015-001',
      decisionNo: 'DEC-20241015-001',
      deviceName: '1号大棚灌溉控制器',
      deviceType: '灌溉控制器',
      commandType: '开启灌溉',
      commandContent: '启动灌溉系统，灌溉量550L',
      parameters: {
        action: 'start',
        volume: 550,
        duration: 15,
        flowRate: 36.7,
      },
      status: '已完成',
      createTime: '2024-10-15 18:05:35',
      sendTime: '2024-10-15 18:05:36',
      completeTime: '2024-10-15 18:20:42',
      executionTime: 906,
      feedback: '灌溉完成，实际用水548L，耗时15分06秒',
    },
    {
      id: 'cmd-2',
      commandNo: 'CMD-20241015-002',
      decisionNo: 'DEC-20241015-002',
      deviceName: '2号大棚卷帘控制器',
      deviceType: '卷帘控制器',
      commandType: '展开卷帘',
      commandContent: '展开遮阳卷帘至50%',
      parameters: {
        action: 'expand',
        percentage: 50,
        speed: 'normal',
      },
      status: '已完成',
      createTime: '2024-10-15 13:20:10',
      sendTime: '2024-10-15 13:20:11',
      completeTime: '2024-10-15 13:20:25',
      executionTime: 14,
      feedback: '卷帘展开完成，当前开度50%',
    },
    {
      id: 'cmd-3',
      commandNo: 'CMD-20241015-003',
      decisionNo: 'DEC-20241015-003',
      deviceName: '3号大棚风机控制器',
      deviceType: '风机控制器',
      commandType: '启动风机',
      commandContent: '启动通风风机，转速60%',
      parameters: {
        action: 'start',
        speed: 60,
        mode: 'auto',
      },
      status: '执行中',
      createTime: '2024-10-15 17:45:20',
      sendTime: '2024-10-15 17:45:21',
      executionTime: 180,
    },
    {
      id: 'cmd-4',
      commandNo: 'CMD-20241015-004',
      decisionNo: 'DEC-20241015-004',
      deviceName: '4号大棚温控系统',
      deviceType: '温控系统',
      commandType: '设置温度',
      commandContent: '设置目标温度22℃',
      parameters: {
        action: 'setTemp',
        targetTemp: 22,
        mode: 'auto',
      },
      status: '失败',
      createTime: '2024-10-15 16:50:00',
      sendTime: '2024-10-15 16:50:01',
      errorMessage: '设备离线，无法发送指令',
    },
  ]);

  // 外部系统数据
  const [externalSystems] = useState<ExternalSystem[]>([
    {
      id: 'sys-1',
      systemName: '智慧农事管理平台',
      systemType: '农事管理系统',
      apiEndpoint: 'https://api.farmwork.com/v1/tasks',
      authType: 'API Key',
      status: '正常',
      lastCallTime: '2024-10-15 17:30:00',
      totalCalls: 1250,
      successRate: 99.5,
      avgResponseTime: 120,
    },
    {
      id: 'sys-2',
      systemName: '精准灌溉控制中心',
      systemType: '灌溉控制系统',
      apiEndpoint: 'https://api.irrigation.com/v2/control',
      authType: 'OAuth 2.0',
      status: '正常',
      lastCallTime: '2024-10-15 18:05:00',
      totalCalls: 856,
      successRate: 98.8,
      avgResponseTime: 95,
    },
    {
      id: 'sys-3',
      systemName: '农业预警推送服务',
      systemType: '预警推送系统',
      apiEndpoint: 'https://api.alert.com/v1/push',
      authType: 'Bearer Token',
      status: '正常',
      lastCallTime: '2024-10-15 14:32:00',
      totalCalls: 320,
      successRate: 100,
      avgResponseTime: 65,
    },
    {
      id: 'sys-4',
      systemName: '农业大数据分析平台',
      systemType: '数据分析平台',
      apiEndpoint: 'https://api.agridata.com/v1/analytics',
      authType: 'API Key',
      status: '异常',
      lastCallTime: '2024-10-15 10:20:00',
      totalCalls: 180,
      successRate: 85.5,
      avgResponseTime: 450,
    },
  ]);

  // API调用记录
  const [apiCalls] = useState<APICall[]>([
    {
      id: 'api-1',
      callNo: 'API-20241015-001',
      systemName: '智慧农事管理平台',
      decisionNo: 'DEC-20241015-002',
      decisionType: '施肥决策',
      apiEndpoint: '/v1/tasks/create',
      method: 'POST',
      requestBody: {
        taskType: 'fertilization',
        fieldId: 'field-002',
        content: '施用复合肥25kg/亩',
        deadline: '2024-10-17',
      },
      responseStatus: 200,
      responseBody: {
        success: true,
        taskId: 'TASK-20241015-056',
        message: '农事任务创建成功',
      },
      callTime: '2024-10-15 17:30:25',
      responseTime: 115,
      success: true,
    },
    {
      id: 'api-2',
      callNo: 'API-20241015-002',
      systemName: '精准灌溉控制中心',
      decisionNo: 'DEC-20241015-001',
      decisionType: '灌溉决策',
      apiEndpoint: '/v2/control/execute',
      method: 'POST',
      requestBody: {
        deviceId: 'DEV-IRT-001',
        action: 'irrigate',
        volume: 550,
        schedule: '2024-10-16 06:00:00',
      },
      responseStatus: 200,
      responseBody: {
        success: true,
        commandId: 'CMD-IRT-20241015-001',
        status: 'scheduled',
      },
      callTime: '2024-10-15 18:05:40',
      responseTime: 88,
      success: true,
    },
    {
      id: 'api-3',
      callNo: 'API-20241015-003',
      systemName: '农业预警推送服务',
      decisionNo: 'DEC-20241015-001',
      decisionType: '病虫害预警',
      apiEndpoint: '/v1/push/alert',
      method: 'POST',
      requestBody: {
        level: 'urgent',
        title: '番茄早疫病预警',
        content: '1号大棚检测到早疫病中度感染',
        recipients: ['manager@farm.com', '13800138000'],
      },
      responseStatus: 200,
      responseBody: {
        success: true,
        messageId: 'MSG-20241015-001',
        sent: 2,
      },
      callTime: '2024-10-15 14:32:30',
      responseTime: 52,
      success: true,
    },
  ]);

  // 统计数据
  const totalDevices = devices.length;
  const onlineDevices = devices.filter(d => d.status === '在线').length;
  const totalCommands = controlCommands.length;
  const successCommands = controlCommands.filter(c => c.status === '已完成').length;
  const totalSystems = externalSystems.length;
  const normalSystems = externalSystems.filter(s => s.status === '正常').length;

  // 设备执行统计
  const deviceExecutionStats = devices.slice(0, 3).map(device => ({
    name: device.deviceName.substring(0, 8),
    执行次数: device.executedCount,
    成功率: device.successRate,
  }));

  // 指令执行趋势
  const commandTrend = [
    { time: '14:00', 成功: 12, 失败: 1 },
    { time: '15:00', 成功: 15, 失败: 0 },
    { time: '16:00', 成功: 18, 失败: 2 },
    { time: '17:00', 成功: 20, 失败: 1 },
    { time: '18:00', 成功: 16, 失败: 0 },
  ];

  // API调用统计
  const apiCallStats = externalSystems.map(sys => ({
    name: sys.systemName.substring(0, 8),
    调用次数: sys.totalCalls,
    响应时间: sys.avgResponseTime,
  }));

  const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6'];

  const getDeviceStatusColor = (status: DeviceStatus) => {
    switch (status) {
      case '在线': return 'bg-success-muted text-success-muted-foreground';
      case '离线': return 'bg-muted text-muted-foreground';
      case '故障': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getCommandStatusColor = (status: CommandStatus) => {
    switch (status) {
      case '待发送': return 'bg-warning-muted text-warning-muted-foreground';
      case '已发送': return 'bg-info-muted text-info-muted-foreground';
      case '执行中': return 'bg-accent-muted text-accent-foreground';
      case '已完成': return 'bg-success-muted text-success-muted-foreground';
      case '失败': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getAPIStatusColor = (status: APIStatus) => {
    switch (status) {
      case '正常': return 'bg-success-muted text-success';
      case '异常': return 'bg-error-muted text-error';
      case '维护中': return 'bg-warning-muted text-warning';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getDeviceIcon = (type: DeviceType) => {
    switch (type) {
      case '灌溉控制器': return <Droplets className="w-4 h-4" />;
      case '卷帘控制器': return <Sun className="w-4 h-4" />;
      case '风机控制器': return <Fan className="w-4 h-4" />;
      case '温控系统': return <Thermometer className="w-4 h-4" />;
      case '补光灯': return <Sun className="w-4 h-4" />;
      default: return <Radio className="w-4 h-4" />;
    }
  };

  const handleSendCommand = (commandNo: string) => {
    toast.success(`指令 ${commandNo} 已发送到设备`);
  };

  const handleRetryCommand = (commandNo: string) => {
    toast.success(`指令 ${commandNo} 正在重试`);
  };

  const handleTestAPI = () => {
    toast.success('API测试请求已发送');
    setTimeout(() => {
      toast.success('API测试成功！响应时间: 95ms');
    }, 1500);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>决策应用</h2>
          <p className="text-sm text-muted-foreground mt-1">
            决策落地执行，形成完整闭环
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新状态
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出日���
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">在线设备</p>
              <p className="mt-2 text-3xl text-success">{onlineDevices}/{totalDevices}</p>
              <p className="text-xs text-success mt-1">设备在线率 {((onlineDevices/totalDevices)*100).toFixed(0)}%</p>
            </div>
            <Wifi className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">指令成功率</p>
              <p className="mt-2 text-3xl text-info">{((successCommands/totalCommands)*100).toFixed(1)}%</p>
              <p className="text-xs text-info mt-1">{successCommands}/{totalCommands} 成功</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">外部系统</p>
              <p className="mt-2 text-3xl text-accent">{normalSystems}/{totalSystems}</p>
              <p className="text-xs text-accent mt-1">正常运行</p>
            </div>
            <Globe className="w-12 h-12 text-accent opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">API调用</p>
              <p className="mt-2 text-3xl text-warning">{apiCalls.length}</p>
              <p className="text-xs text-warning mt-1">今日调用</p>
            </div>
            <Send className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="device-control">设备控制集成</TabsTrigger>
          <TabsTrigger value="external-system">外部系统联动</TabsTrigger>
        </TabsList>

        {/* 设备控制集成 */}
        <TabsContent value="device-control" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-info-muted/50 to-info-muted border-info/30">
            <div className="flex items-start gap-2">
              <Radio className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
              <div className="text-sm text-info-muted-foreground">
                <p className="mb-2">设备控制集成功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动执行</strong>: 可自动执行的决策生成标准控制指令</li>
                  <li>• <strong>IoT集成</strong>: 通过IoT平台下发指令至设备</li>
                  <li>• <strong>状态跟踪</strong>: 实时跟踪指令执行状态</li>
                  <li>• <strong>结果反馈</strong>: 设备执行结果实时回传</li>
                  <li>• <strong>闭环控制</strong>: 决策-动作-反馈完整闭环</li>
                  <li>• <strong>设备管理</strong>: 集成设备注册、监控、维护</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 设备列表 */}
          <Card>
            <div className="p-4 border-b">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <Plug className="w-5 h-5 text-info" />
                  接入设备列表
                </h3>
                <Button size="sm" onClick={() => {
                  setSelectedDevice(null);
                  setShowDeviceDialog(true);
                }}>
                  <Plus className="w-3 h-3 mr-1" />
                  添加设备
                </Button>
              </div>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>设备编号</TableHead>
                  <TableHead>设备名称</TableHead>
                  <TableHead>设备类型</TableHead>
                  <TableHead>位置</TableHead>
                  <TableHead>IP地址</TableHead>
                  <TableHead>固件版本</TableHead>
                  <TableHead>执行统计</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {devices.map((device) => (
                  <TableRow key={device.id}>
                    <TableCell className="font-mono text-xs">{device.deviceNo}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {getDeviceIcon(device.deviceType)}
                        {device.deviceName}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.deviceType}</Badge>
                    </TableCell>
                    <TableCell className="text-xs">{device.location}</TableCell>
                    <TableCell className="font-mono text-xs">{device.ipAddress}</TableCell>
                    <TableCell className="text-xs">{device.firmware}</TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>执行: {device.executedCount}次</div>
                        <div className="text-success">成功率: {device.successRate}%</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <Badge className={getDeviceStatusColor(device.status)}>
                          {device.status}
                        </Badge>
                        <div className="text-xs text-muted-foreground">
                          {device.lastOnlineTime.substring(11)}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedDevice(device);
                          setShowDeviceDialog(true);
                        }}>
                          <Eye className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline">
                          <Settings className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 控制指令列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Zap className="w-5 h-5 text-success" />
                控制指令记录
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>指令编号</TableHead>
                  <TableHead>决策编号</TableHead>
                  <TableHead>目标设备</TableHead>
                  <TableHead>指令类型</TableHead>
                  <TableHead>指令内容</TableHead>
                  <TableHead>执行时间</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>反馈</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {controlCommands.map((command) => (
                  <TableRow key={command.id}>
                    <TableCell className="font-mono text-xs">{command.commandNo}</TableCell>
                    <TableCell className="font-mono text-xs">{command.decisionNo}</TableCell>
                    <TableCell>
                      <div className="text-xs">
                        <div className="font-medium">{command.deviceName}</div>
                        <div className="text-muted-foreground">{command.deviceType}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{command.commandType}</Badge>
                    </TableCell>
                    <TableCell className="text-xs max-w-xs">
                      {command.commandContent}
                    </TableCell>
                    <TableCell className="text-xs">
                      {command.executionTime ? `${command.executionTime}秒` : '-'}
                    </TableCell>
                    <TableCell>
                      <Badge className={getCommandStatusColor(command.status)}>
                        {command.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs max-w-xs">
                        {command.feedback && (
                          <div className="text-success">{command.feedback}</div>
                        )}
                        {command.errorMessage && (
                          <div className="text-destructive">{command.errorMessage}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedCommand(command);
                          setShowCommandDialog(true);
                        }}>
                          <Eye className="w-3 h-3" />
                        </Button>
                        {command.status === '失败' && (
                          <Button size="sm" variant="outline" onClick={() => handleRetryCommand(command.commandNo)}>
                            <RefreshCw className="w-3 h-3" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 设备执行统计 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-info" />
                设备执行统计
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <BarChart data={deviceExecutionStats}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip />
                  <Legend />
                  <Bar yAxisId="left" dataKey="执行次数" fill="#3b82f6" />
                  <Line yAxisId="right" dataKey="成功率" stroke="#10b981" strokeWidth={2} />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-success" />
                指令执行趋势
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <AreaChart data={commandTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Area type="monotone" dataKey="成功" stackId="1" stroke="#10b981" fill="#10b981" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="失败" stackId="1" stroke="#ef4444" fill="#ef4444" fillOpacity={0.6} />
                </AreaChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 外部系统联动 */}
        <TabsContent value="external-system" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-accent-muted/50 to-accent-muted border-accent/30">
            <div className="flex items-start gap-2">
              <Globe className="w-5 h-5 text-accent flex-shrink-0 mt-0.5" />
              <div className="text-sm text-accent-muted-foreground">
                <p className="mb-2">外部系统联动功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>RESTful API</strong>: 提供标准API接口</li>
                  <li>• <strong>决策推送</strong>: 将决策结果推送至第三方系统</li>
                  <li>• <strong>多系统支持</strong>: 农事管理、灌溉控制、预警推送等</li>
                  <li>• <strong>无缝协同</strong>: 与现有农业信息化系统集成</li>
                  <li>• <strong>认证安全</strong>: 支持API Key、OAuth等认证方式</li>
                  <li>• <strong>调用监控</strong>: 实时监控API调用状态和性能</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 外部系统列表 */}
          <Card>
            <div className="p-4 border-b">
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <Server className="w-5 h-5 text-accent" />
                  接入系统列表
                </h3>
                <Button size="sm" onClick={() => {
                  setSelectedSystem(null);
                  setShowSystemDialog(true);
                }}>
                  <Plus className="w-3 h-3 mr-1" />
                  添加系统
                </Button>
              </div>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>系统名称</TableHead>
                  <TableHead>系统类型</TableHead>
                  <TableHead>API端点</TableHead>
                  <TableHead>认证方式</TableHead>
                  <TableHead>调用统计</TableHead>
                  <TableHead>性能指标</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {externalSystems.map((system) => (
                  <TableRow key={system.id}>
                    <TableCell className="font-medium">{system.systemName}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{system.systemType}</Badge>
                    </TableCell>
                    <TableCell className="font-mono text-xs max-w-xs truncate">
                      {system.apiEndpoint}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1 text-xs">
                        <Shield className="w-3 h-3" />
                        {system.authType}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>调用: {system.totalCalls}次</div>
                        <div className="text-success">成功率: {system.successRate}%</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        <div>响应: {system.avgResponseTime}ms</div>
                        {system.lastCallTime && (
                          <div className="text-muted-foreground">
                            最近: {system.lastCallTime.substring(11)}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getAPIStatusColor(system.status)}>
                        {system.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedSystem(system);
                          setShowAPITestDialog(true);
                        }}>
                          <PlayCircle className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedSystem(system);
                          setShowSystemDialog(true);
                        }}>
                          <Edit className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* API调用记录 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <History className="w-5 h-5 text-success" />
                API调用记录
              </h3>
            </div>
            <div className="divide-y">
              {apiCalls.map((call) => (
                <div key={call.id} className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h5>{call.systemName}</h5>
                        <Badge variant="outline">{call.method}</Badge>
                        <Badge className={call.success ? 'bg-success-muted text-success' : 'bg-error-muted text-error'}>
                          {call.responseStatus}
                        </Badge>
                      </div>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {call.callTime}
                        </span>
                        <span className="flex items-center gap-1">
                          <Zap className="w-3 h-3" />
                          {call.responseTime}ms
                        </span>
                        <span>#{call.callNo}</span>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-info/10 rounded">
                      <p className="text-xs text-muted-foreground mb-1">请求信息</p>
                      <div className="space-y-1">
                        <p className="text-xs"><strong>端点:</strong> {call.apiEndpoint}</p>
                        <p className="text-xs"><strong>决策:</strong> {call.decisionNo} ({call.decisionType})</p>
                        <details className="text-xs">
                          <summary className="cursor-pointer text-info">查看请求体</summary>
                          <pre className="mt-2 p-2 bg-white rounded text-xs overflow-auto">
                            {JSON.stringify(call.requestBody, null, 2)}
                          </pre>
                        </details>
                      </div>
                    </div>

                    <div className="p-3 bg-success/10 rounded">
                      <p className="text-xs text-muted-foreground mb-1">响应信息</p>
                      <div className="space-y-1">
                        <p className="text-xs"><strong>状态:</strong> {call.responseStatus}</p>
                        <p className="text-xs"><strong>耗时:</strong> {call.responseTime}ms</p>
                        {call.responseBody && (
                          <details className="text-xs">
                            <summary className="cursor-pointer text-success">查看响应体</summary>
                            <pre className="mt-2 p-2 bg-white rounded text-xs overflow-auto">
                              {JSON.stringify(call.responseBody, null, 2)}
                            </pre>
                          </details>
                        )}
                        {call.errorMessage && (
                          <p className="text-xs text-destructive">{call.errorMessage}</p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* API调用统计 */}
          <Card className="p-4">
            <h4 className="mb-4 flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-accent" />
              API调用统计
            </h4>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={apiCallStats}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <RechartsTooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="调用次数" fill="#8b5cf6" />
                <Bar yAxisId="right" dataKey="响应时间" fill="#10b981" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 设备详情对话框 */}
      <Dialog open={showDeviceDialog} onOpenChange={setShowDeviceDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{selectedDevice ? '设备详情' : '添加设备'}</DialogTitle>
            <DialogDescription>
              {selectedDevice ? `设备编号: ${selectedDevice.deviceNo}` : '配置新的IoT控制设备'}
            </DialogDescription>
          </DialogHeader>

          {selectedDevice ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>设备名称</Label>
                  <div className="field-value">{selectedDevice.deviceName}</div>
                </div>
                <div>
                  <Label>设备类型</Label>
                  <div className="field-value">{selectedDevice.deviceType}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>安装位置</Label>
                  <div className="field-value">{selectedDevice.location}</div>
                </div>
                <div>
                  <Label>IP地址</Label>
                  <div className="field-value font-mono">{selectedDevice.ipAddress}</div>
                </div>
              </div>
              <div>
                <Label>支持的指令</Label>
                <div className="field-value">
                  <div className="flex flex-wrap gap-2">
                    {selectedDevice.supportCommands.map((cmd, idx) => (
                      <Badge key={idx} variant="outline">{cmd}</Badge>
                    ))}
                  </div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>固件版本</Label>
                  <div className="field-value">{selectedDevice.firmware}</div>
                </div>
                <div>
                  <Label>设备状态</Label>
                  <div className="field-value">
                    <Badge className={getDeviceStatusColor(selectedDevice.status)}>
                      {selectedDevice.status}
                    </Badge>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>设备名称</Label>
                  <Input placeholder="输入设备名称" />
                </div>
                <div>
                  <Label>设备类型</Label>
                  <Select>
                    <SelectTrigger>
                      <SelectValue placeholder="选择设备类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="irrigation">灌溉控制器</SelectItem>
                      <SelectItem value="curtain">卷帘控制器</SelectItem>
                      <SelectItem value="fan">风机控制器</SelectItem>
                      <SelectItem value="temp">温控系统</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>IP地址</Label>
                  <Input placeholder="192.168.1.100" />
                </div>
                <div>
                  <Label>端口</Label>
                  <Input placeholder="8080" />
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeviceDialog(false)}>
              关闭
            </Button>
            {!selectedDevice && (
              <Button>添加设备</Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 指令详情对话框 */}
      <Dialog open={showCommandDialog} onOpenChange={setShowCommandDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>指令详情</DialogTitle>
            <DialogDescription>
              指令编号: {selectedCommand?.commandNo}
            </DialogDescription>
          </DialogHeader>

          {selectedCommand && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>关联决策</Label>
                  <div className="field-value font-mono">{selectedCommand.decisionNo}</div>
                </div>
                <div>
                  <Label>目标设备</Label>
                  <div className="field-value">{selectedCommand.deviceName}</div>
                </div>
              </div>
              <div>
                <Label>指令内容</Label>
                <div className="field-value">{selectedCommand.commandContent}</div>
              </div>
              <div>
                <Label>指令参数</Label>
                <div className="field-value bg-info/10">
                  <pre className="text-xs">{JSON.stringify(selectedCommand.parameters, null, 2)}</pre>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>执行状态</Label>
                  <div className="field-value">
                    <Badge className={getCommandStatusColor(selectedCommand.status)}>
                      {selectedCommand.status}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>执行耗时</Label>
                  <div className="field-value">{selectedCommand.executionTime ? `${selectedCommand.executionTime}秒` : '-'}</div>
                </div>
              </div>
              {selectedCommand.feedback && (
                <div>
                  <Label>执行反馈</Label>
                  <div className="field-value bg-success/10 text-success">
                    {selectedCommand.feedback}
                  </div>
                </div>
              )}
              {selectedCommand.errorMessage && (
                <div>
                  <Label>错误信息</Label>
                  <div className="field-value bg-destructive/10 text-destructive">
                    {selectedCommand.errorMessage}
                  </div>
                </div>
              )}
            </div>
          )}

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

      {/* 外部系统配置对话框 */}
      <Dialog open={showSystemDialog} onOpenChange={setShowSystemDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{selectedSystem ? '系统配置' : '添加系统'}</DialogTitle>
            <DialogDescription>
              {selectedSystem ? selectedSystem.systemName : '配置新的外部系统接口'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>系统名称</Label>
              <Input placeholder="输入系统名称" defaultValue={selectedSystem?.systemName} />
            </div>
            <div>
              <Label>系统类型</Label>
              <Select defaultValue={selectedSystem?.systemType}>
                <SelectTrigger>
                  <SelectValue placeholder="选择系统类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="农事管理系统">农事管理系统</SelectItem>
                  <SelectItem value="灌溉控制系统">灌溉控制系统</SelectItem>
                  <SelectItem value="预警推送系统">预警推送系统</SelectItem>
                  <SelectItem value="数据分析平台">数据分析平台</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>API端点</Label>
              <Input placeholder="https://api.example.com/v1" defaultValue={selectedSystem?.apiEndpoint} />
            </div>
            <div>
              <Label>认证方式</Label>
              <Select defaultValue={selectedSystem?.authType}>
                <SelectTrigger>
                  <SelectValue placeholder="选择认证方式" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="API Key">API Key</SelectItem>
                  <SelectItem value="OAuth 2.0">OAuth 2.0</SelectItem>
                  <SelectItem value="Bearer Token">Bearer Token</SelectItem>
                  <SelectItem value="Basic Auth">Basic Auth</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>认证凭证</Label>
              <Input type="password" placeholder="输入API Key或Token" />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSystemDialog(false)}>
              取消
            </Button>
            <Button>保存配置</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* API测试对话框 */}
      <Dialog open={showAPITestDialog} onOpenChange={setShowAPITestDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>API测试</DialogTitle>
            <DialogDescription>
              测试系统: {selectedSystem?.systemName}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>API端点</Label>
              <div className="field-value font-mono text-sm">
                {selectedSystem?.apiEndpoint}
              </div>
            </div>
            <div>
              <Label>请求方法</Label>
              <Select defaultValue="POST">
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="GET">GET</SelectItem>
                  <SelectItem value="POST">POST</SelectItem>
                  <SelectItem value="PUT">PUT</SelectItem>
                  <SelectItem value="DELETE">DELETE</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>请求体 (JSON)</Label>
              <Textarea 
                rows={8} 
                placeholder='{"key": "value"}'
                className="font-mono text-sm"
                defaultValue={JSON.stringify({
                  decisionType: "irrigation",
                  fieldId: "field-001",
                  action: "irrigate",
                  volume: 550
                }, null, 2)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAPITestDialog(false)}>
              取消
            </Button>
            <Button onClick={handleTestAPI}>
              <PlayCircle className="w-4 h-4 mr-2" />
              发送测试请求
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
