import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import {
  Search,
  Eye,
  Cpu,
  CheckCircle,
  AlertCircle,
  Link2,
  Calendar,
  Package,
  Wifi,
  WifiOff,
  AlertTriangle,
  Info,
  RefreshCw,
  Signal,
  Battery,
  MapPin,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

// AI系统物联设备接口
type DeviceType = '气象站' | '土壤传感器' | '摄像头' | '水质传感器' | '环境监测站';
type DeviceStatus = '在线' | '离线' | '故障' | '维护中';
type Protocol = 'MQTT' | 'HTTP' | 'CoAP' | 'WebSocket';

interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: DeviceType;
  deviceTypeId?: string;
  manufacturer: string;
  model: string;
  location: string;
  fieldId: string;
  fieldName: string;
  protocol: Protocol;
  ipAddress?: string;
  mqttTopic?: string;
  status: DeviceStatus;
  bindingStatus: '未绑定' | '已绑定';
  bindingSystem?: string;
  lastReportTime: string;
  dataFrequency: string;
  batteryLevel?: number;
  signalStrength?: number;
  sensors: {
    name: string;
    unit: string;
    currentValue: number;
    normalRange: string;
  }[];
}

export function WaterFertilizerComponent() {
  const [devices, setDevices] = useState<IoTDevice[]>([]);
  const [filteredDevices, setFilteredDevices] = useState<IoTDevice[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [bindingFilter, setBindingFilter] = useState<string>('all');
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [viewingDevice, setViewingDevice] = useState<IoTDevice | null>(null);

  // 从AI系统加载物联设备数据
  useEffect(() => {
    loadIoTDevices();
  }, []);

  // 从AI系统加载物联设备数据
  const loadIoTDevices = () => {
    // 模拟从localStorage读取AI系统的物联设备数据
    // 实际应该从 localStorage.getItem('smart_agriculture_ai_iot_devices')
    // 这里使用模拟数据，实际部署时会从AI数据中心读取
    const mockDevices: IoTDevice[] = [
      {
        id: 'iot-1',
        code: 'WS-2024-001',
        name: '1号气象站',
        type: '气象站',
        deviceTypeId: 'device-type-2',
        manufacturer: '华为',
        model: 'HW-WS-Pro',
        location: '1号大棚北侧',
        fieldId: 'field_001',
        fieldName: '1号大棚',
        protocol: 'MQTT',
        mqttTopic: 'farm/weather/station01',
        status: '在线',
        bindingStatus: '已绑定',
        bindingSystem: '智能灌溉控制系统',
        lastReportTime: '2024-10-15 14:05:00',
        dataFrequency: '每5分钟',
        batteryLevel: 85,
        signalStrength: 92,
        sensors: [
          { name: '温度', unit: '℃', currentValue: 24.5, normalRange: '-10~40' },
          { name: '湿度', unit: '%', currentValue: 68, normalRange: '0~100' },
          { name: '气压', unit: 'hPa', currentValue: 1013, normalRange: '950~1050' },
          { name: '风速', unit: 'm/s', currentValue: 3.2, normalRange: '0~30' },
        ],
      },
      {
        id: 'iot-2',
        code: 'SS-2024-012',
        name: '2号土壤传感器',
        type: '土壤传感器',
        deviceTypeId: 'device-type-1',
        manufacturer: '中科院',
        model: 'CAS-SS-300',
        location: '3号地块中心',
        fieldId: 'field_003',
        fieldName: '3号地块',
        protocol: 'MQTT',
        mqttTopic: 'farm/soil/sensor02',
        status: '在线',
        bindingStatus: '已绑定',
        bindingSystem: '智能灌溉控制系统',
        lastReportTime: '2024-10-15 14:03:00',
        dataFrequency: '每10分钟',
        batteryLevel: 72,
        signalStrength: 88,
        sensors: [
          { name: '土壤温度', unit: '℃', currentValue: 18.3, normalRange: '0~35' },
          { name: '土壤湿度', unit: '%', currentValue: 45, normalRange: '20~80' },
          { name: 'EC值', unit: 'mS/cm', currentValue: 1.2, normalRange: '0.5~3' },
          { name: 'pH值', unit: '', currentValue: 6.8, normalRange: '5.5~8.5' },
        ],
      },
      {
        id: 'iot-3',
        code: 'CAM-2024-005',
        name: '3号监控摄像头',
        type: '摄像头',
        manufacturer: '海康威视',
        model: 'HIK-CAM-4K',
        location: '2号大棚入口',
        fieldId: 'field_002',
        fieldName: '2号大棚',
        protocol: 'HTTP',
        ipAddress: '192.168.1.105',
        status: '在线',
        bindingStatus: '未绑定',
        lastReportTime: '2024-10-15 14:05:30',
        dataFrequency: '实时',
        signalStrength: 95,
        sensors: [
          { name: '图像质量', unit: 'score', currentValue: 98, normalRange: '80~100' },
          { name: '存储空间', unit: '%', currentValue: 45, normalRange: '0~90' },
        ],
      },
      {
        id: 'iot-4',
        code: 'WS-2024-002',
        name: '2号气象站',
        type: '气象站',
        deviceTypeId: 'device-type-2',
        manufacturer: '华为',
        model: 'HW-WS-Pro',
        location: '6号地块东侧',
        fieldId: 'field_006',
        fieldName: '6号地块',
        protocol: 'MQTT',
        mqttTopic: 'farm/weather/station02',
        status: '离线',
        bindingStatus: '未绑定',
        lastReportTime: '2024-10-15 10:25:00',
        dataFrequency: '每5分钟',
        batteryLevel: 15,
        signalStrength: 0,
        sensors: [
          { name: '温度', unit: '℃', currentValue: 0, normalRange: '-10~40' },
          { name: '湿度', unit: '%', currentValue: 0, normalRange: '0~100' },
        ],
      },
      {
        id: 'iot-5',
        code: 'WQ-2024-008',
        name: '1号水质传感器',
        type: '水质传感器',
        manufacturer: '岛津',
        model: 'SH-WQ-200',
        location: '4号地块灌溉主管',
        fieldId: 'field_004',
        fieldName: '4号地块',
        protocol: 'MQTT',
        mqttTopic: 'farm/water/quality01',
        status: '在线',
        bindingStatus: '未绑定',
        lastReportTime: '2024-10-15 14:00:00',
        dataFrequency: '每15分钟',
        batteryLevel: 90,
        signalStrength: 85,
        sensors: [
          { name: 'pH值', unit: '', currentValue: 7.2, normalRange: '6.5~8.5' },
          { name: 'EC值', unit: 'mS/cm', currentValue: 1.5, normalRange: '0.5~3' },
          { name: '溶解氧', unit: 'mg/L', currentValue: 8.5, normalRange: '5~15' },
          { name: '浊度', unit: 'NTU', currentValue: 2.1, normalRange: '0~5' },
        ],
      },
      {
        id: 'iot-6',
        code: 'ENV-2024-003',
        name: '1号环境监测站',
        type: '环境监测站',
        manufacturer: '中科院',
        model: 'CAS-ENV-500',
        location: '5号大棚中心',
        fieldId: 'field_005',
        fieldName: '5号大棚',
        protocol: 'MQTT',
        mqttTopic: 'farm/env/station01',
        status: '在线',
        bindingStatus: '已绑定',
        bindingSystem: '地块环境监测系统',
        lastReportTime: '2024-10-15 14:04:00',
        dataFrequency: '每5分钟',
        batteryLevel: 78,
        signalStrength: 90,
        sensors: [
          { name: '温度', unit: '℃', currentValue: 26.5, normalRange: '10~35' },
          { name: '湿度', unit: '%', currentValue: 72, normalRange: '30~80' },
          { name: 'CO2浓度', unit: 'ppm', currentValue: 450, normalRange: '350~1000' },
          { name: '光照强度', unit: 'lux', currentValue: 35000, normalRange: '0~100000' },
        ],
      },
      {
        id: 'iot-7',
        code: 'SS-2024-015',
        name: '5号土壤传感器',
        type: '土壤传感器',
        manufacturer: '中科院',
        model: 'CAS-SS-300',
        location: '7号大棚东南',
        fieldId: 'field_007',
        fieldName: '7号大棚',
        protocol: 'MQTT',
        mqttTopic: 'farm/soil/sensor05',
        status: '故障',
        bindingStatus: '未绑定',
        lastReportTime: '2024-10-14 16:30:00',
        dataFrequency: '每10分钟',
        batteryLevel: 5,
        signalStrength: 25,
        sensors: [
          { name: '土壤温度', unit: '℃', currentValue: 0, normalRange: '0~35' },
          { name: '土壤湿度', unit: '%', currentValue: 0, normalRange: '20~80' },
        ],
      },
      {
        id: 'iot-8',
        code: 'WQ-2024-010',
        name: '2号水质传感器',
        type: '水质传感器',
        manufacturer: '岛津',
        model: 'SH-WQ-200',
        location: '8号地块灌溉支管',
        fieldId: 'field_008',
        fieldName: '8号地块',
        protocol: 'MQTT',
        mqttTopic: 'farm/water/quality02',
        status: '维护中',
        bindingStatus: '未绑定',
        lastReportTime: '2024-10-15 09:00:00',
        dataFrequency: '每15分钟',
        batteryLevel: 0,
        signalStrength: 0,
        sensors: [
          { name: 'pH值', unit: '', currentValue: 0, normalRange: '6.5~8.5' },
          { name: 'EC值', unit: 'mS/cm', currentValue: 0, normalRange: '0.5~3' },
        ],
      },
    ];

    setDevices(mockDevices);
    setFilteredDevices(mockDevices);
    
    if (mockDevices.length > 0) {
      toast.success(`已从AI系统加载 ${mockDevices.length} 个物联设备`);
    }
  };

  // 搜索和筛选
  useEffect(() => {
    let filtered = devices;

    // 关键词搜索
    if (searchKeyword) {
      filtered = filtered.filter(
        device =>
          device.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          device.code.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          device.type.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          device.manufacturer.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          device.location.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          device.fieldName.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    // 状态筛选
    if (statusFilter !== 'all') {
      filtered = filtered.filter(device => device.status === statusFilter);
    }

    // 类型筛选
    if (typeFilter !== 'all') {
      filtered = filtered.filter(device => device.type === typeFilter);
    }

    // 绑定状态筛选
    if (bindingFilter !== 'all') {
      filtered = filtered.filter(device => device.bindingStatus === bindingFilter);
    }

    setFilteredDevices(filtered);
  }, [searchKeyword, statusFilter, typeFilter, bindingFilter, devices]);

  // 查看详情
  const handleViewDevice = (device: IoTDevice) => {
    setViewingDevice(device);
    setShowViewDialog(true);
  };

  // 获取状态样式
  const getStatusBadge = (status: DeviceStatus) => {
    switch (status) {
      case '在线':
        return (
          <Badge className="bg-green-500 text-white">
            <Wifi className="w-3 h-3 mr-1" />
            在线
          </Badge>
        );
      case '离线':
        return (
          <Badge className="bg-gray-500 text-white">
            <WifiOff className="w-3 h-3 mr-1" />
            离线
          </Badge>
        );
      case '故障':
        return (
          <Badge className="bg-red-500 text-white">
            <AlertCircle className="w-3 h-3 mr-1" />
            故障
          </Badge>
        );
      case '维护中':
        return (
          <Badge className="bg-yellow-500 text-white">
            <AlertTriangle className="w-3 h-3 mr-1" />
            维护中
          </Badge>
        );
    }
  };

  // 获取绑定状态样式
  const getBindingStatusBadge = (status: '未绑定' | '已绑定', system?: string) => {
    if (status === '已绑定') {
      return (
        <div className="flex items-center gap-2">
          <Badge className="bg-blue-100 text-blue-800">
            <Link2 className="w-3 h-3 mr-1" />
            已绑定
          </Badge>
          {system && <span className="text-xs text-muted-foreground">{system}</span>}
        </div>
      );
    }
    return (
      <Badge variant="outline" className="text-gray-600">
        未绑定
      </Badge>
    );
  };

  // 统计数据
  const totalDevices = devices.length;
  const onlineDevices = devices.filter(d => d.status === '在线').length;
  const offlineDevices = devices.filter(d => d.status === '离线').length;
  const faultDevices = devices.filter(d => d.status === '故障').length;
  const boundDevices = devices.filter(d => d.bindingStatus === '已绑定').length;

  // 获取唯一的设备类型列表
  const deviceTypes = Array.from(new Set(devices.map(d => d.type)));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">水肥机部件配置</h2>
          <p className="text-muted-foreground">
            数据来源：AI作物模型精准决策系统 - 全域数据感知中心 - 物联设备数据接入（只读模式）
          </p>
        </div>
        <Button variant="outline" onClick={loadIoTDevices}>
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新数据
        </Button>
      </div>

      {/* 只读模式提示 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <p className="text-blue-900">
              <strong>只读模式</strong>：本页面数据来自AI系统的物联设备数据接入，仅供查询查看。
            </p>
            <p className="text-sm text-blue-700 mt-1">
              如需添加或修改设备，请前往：<strong>AI作物模型精准决策系统 → 全域数据感知中心 → 物联设备数据接入</strong>
            </p>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-5 gap-4">
        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">设备总数</p>
              <p className="mt-2 text-2xl text-blue-600">{totalDevices}</p>
            </div>
            <Package className="w-10 h-10 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">在线设备</p>
              <p className="mt-2 text-2xl text-green-600">{onlineDevices}</p>
            </div>
            <CheckCircle className="w-10 h-10 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-gray-50 to-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">离线设备</p>
              <p className="mt-2 text-2xl text-gray-600">{offlineDevices}</p>
            </div>
            <WifiOff className="w-10 h-10 text-gray-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">故障设备</p>
              <p className="mt-2 text-2xl text-red-600">{faultDevices}</p>
            </div>
            <AlertCircle className="w-10 h-10 text-red-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">已绑定</p>
              <p className="mt-2 text-2xl text-purple-600">{boundDevices}</p>
            </div>
            <Link2 className="w-10 h-10 text-purple-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索设备名称、编号、类型、厂商、位置、地块..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue placeholder="状态筛选" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="在线">在线</SelectItem>
              <SelectItem value="离线">离线</SelectItem>
              <SelectItem value="故障">故障</SelectItem>
              <SelectItem value="维护中">维护中</SelectItem>
            </SelectContent>
          </Select>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="类型筛选" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              {deviceTypes.map(type => (
                <SelectItem key={type} value={type}>{type}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={bindingFilter} onValueChange={setBindingFilter}>
            <SelectTrigger className="w-40">
              <SelectValue placeholder="绑定状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部</SelectItem>
              <SelectItem value="已绑定">已绑定</SelectItem>
              <SelectItem value="未绑定">未绑定</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 设备列表 */}
      <Card className="p-4">
        <div className="overflow-x-auto">
          <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>
              {filteredDevices.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
                    {devices.length === 0 ? (
                      <div>
                        <Package className="w-12 h-12 mx-auto mb-2 opacity-30" />
                        <p>暂无设备数据</p>
                        <p className="text-sm mt-1">请先在AI系统-物联设备数据接入中添加设备</p>
                      </div>
                    ) : (
                      '没有符合条件的设备'
                    )}
                  </TableCell>
                </TableRow>
              ) : (
                filteredDevices.map((device) => (
                  <TableRow key={device.id} className="hover:bg-gray-50">
                    <TableCell>
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                        {device.code}
                      </code>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Cpu className="w-4 h-4 text-blue-600" />
                        {device.name}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.type}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">
                        <div>{device.manufacturer}</div>
                        <div className="text-muted-foreground">{device.model}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">
                        <div className="flex items-center gap-1">
                          <MapPin className="w-3 h-3 text-muted-foreground" />
                          {device.location}
                        </div>
                        <div className="text-muted-foreground">{device.fieldName}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs">
                        {device.protocol}
                      </Badge>
                    </TableCell>
                    <TableCell>{getStatusBadge(device.status)}</TableCell>
                    <TableCell>{getBindingStatusBadge(device.bindingStatus, device.bindingSystem)}</TableCell>
                    <TableCell>
                      {device.signalStrength !== undefined && (
                        <div className="flex items-center gap-2">
                          <Signal className="w-4 h-4 text-muted-foreground" />
                          <span className="text-sm">{device.signalStrength}%</span>
                        </div>
                      )}
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDevice(device)}
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        查看
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 查看设备详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>设备详情</DialogTitle>
            <DialogDescription>
              查看物联设备的完整信息（只读）
            </DialogDescription>
          </DialogHeader>
          {viewingDevice && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h3 className="mb-3 text-green-800">基本信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>设备编号</Label>
                    <div className="field-value">
                      <code className="bg-gray-100 px-2 py-1 rounded">{viewingDevice.code}</code>
                    </div>
                  </div>
                  <div>
                    <Label>设备名称</Label>
                    <div className="field-value">{viewingDevice.name}</div>
                  </div>
                  <div>
                    <Label>设备类型</Label>
                    <div className="field-value">
                      <Badge variant="outline">{viewingDevice.type}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>当前状态</Label>
                    <div className="field-value">{getStatusBadge(viewingDevice.status)}</div>
                  </div>
                </div>
              </div>

              {/* 设备规格 */}
              <div>
                <h3 className="mb-3 text-green-800">设备规格</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>生产厂商</Label>
                    <div className="field-value">{viewingDevice.manufacturer}</div>
                  </div>
                  <div>
                    <Label>产品型号</Label>
                    <div className="field-value">{viewingDevice.model}</div>
                  </div>
                  {viewingDevice.deviceTypeId && (
                    <div>
                      <Label>设备类型ID</Label>
                      <div className="field-value">
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {viewingDevice.deviceTypeId}
                        </code>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 位置信息 */}
              <div>
                <h3 className="mb-3 text-green-800">位置信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>安装位置</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4 text-muted-foreground" />
                        {viewingDevice.location}
                      </div>
                    </div>
                  </div>
                  <div>
                    <Label>所属地块</Label>
                    <div className="field-value">{viewingDevice.fieldName}</div>
                  </div>
                  <div>
                    <Label>地块ID</Label>
                    <div className="field-value">
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                        {viewingDevice.fieldId}
                      </code>
                    </div>
                  </div>
                </div>
              </div>

              {/* 通信配置 */}
              <div>
                <h3 className="mb-3 text-green-800">通信配置</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>通信协议</Label>
                    <div className="field-value">
                      <Badge variant="outline">{viewingDevice.protocol}</Badge>
                    </div>
                  </div>
                  {viewingDevice.ipAddress && (
                    <div>
                      <Label>IP地址</Label>
                      <div className="field-value">
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {viewingDevice.ipAddress}
                        </code>
                      </div>
                    </div>
                  )}
                  {viewingDevice.mqttTopic && (
                    <div>
                      <Label>MQTT主题</Label>
                      <div className="field-value">
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {viewingDevice.mqttTopic}
                        </code>
                      </div>
                    </div>
                  )}
                  <div>
                    <Label>数据频率</Label>
                    <div className="field-value">{viewingDevice.dataFrequency}</div>
                  </div>
                </div>
              </div>

              {/* 绑定信息 */}
              <div>
                <h3 className="mb-3 text-green-800">绑定信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>绑定状态</Label>
                    <div className="field-value">
                      {getBindingStatusBadge(viewingDevice.bindingStatus, viewingDevice.bindingSystem)}
                    </div>
                  </div>
                  {viewingDevice.bindingSystem && (
                    <div>
                      <Label>绑定系统</Label>
                      <div className="field-value">{viewingDevice.bindingSystem}</div>
                    </div>
                  )}
                </div>
              </div>

              {/* 运行状态 */}
              <div>
                <h3 className="mb-3 text-green-800">运行状态</h3>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <Label>最后上报时间</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-muted-foreground" />
                        {viewingDevice.lastReportTime}
                      </div>
                    </div>
                  </div>
                  {viewingDevice.batteryLevel !== undefined && (
                    <div>
                      <Label>电池电量</Label>
                      <div className="field-value">
                        <div className="flex items-center gap-2">
                          <Battery className={`w-4 h-4 ${viewingDevice.batteryLevel > 50 ? 'text-green-600' : viewingDevice.batteryLevel > 20 ? 'text-yellow-600' : 'text-red-600'}`} />
                          <span>{viewingDevice.batteryLevel}%</span>
                        </div>
                      </div>
                    </div>
                  )}
                  {viewingDevice.signalStrength !== undefined && (
                    <div>
                      <Label>信号强度</Label>
                      <div className="field-value">
                        <div className="flex items-center gap-2">
                          <Signal className={`w-4 h-4 ${viewingDevice.signalStrength > 70 ? 'text-green-600' : viewingDevice.signalStrength > 40 ? 'text-yellow-600' : 'text-red-600'}`} />
                          <span>{viewingDevice.signalStrength}%</span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 传感器数据 */}
              {viewingDevice.sensors && viewingDevice.sensors.length > 0 && (
                <div>
                  <h3 className="mb-3 text-green-800">传感器数据</h3>
                  <div className="bg-gray-50 p-4 rounded border">
                    <div className="grid grid-cols-2 gap-4">
                      {viewingDevice.sensors.map((sensor, index) => (
                        <div key={index} className="bg-white p-3 rounded border">
                          <div className="flex items-center justify-between mb-2">
                            <span className="text-sm text-muted-foreground">{sensor.name}</span>
                            <Badge variant="outline" className="text-xs">{sensor.unit}</Badge>
                          </div>
                          <div className="flex items-baseline gap-2">
                            <span className="text-2xl text-green-600">{sensor.currentValue}</span>
                            <span className="text-xs text-muted-foreground">
                              范围: {sensor.normalRange}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* 数据来源说明 */}
              <div className="bg-blue-50 p-3 rounded border border-blue-200">
                <div className="flex items-start gap-2">
                  <Info className="w-4 h-4 text-blue-600 mt-0.5" />
                  <p className="text-sm text-blue-900">
                    此设备信息来自AI系统-物联设备数据接入。如需修改设备配置，请前往AI系统进行操作。
                  </p>
                </div>
              </div>

              <div className="flex justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowViewDialog(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
