import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Eye, Info, Search, RefreshCw, Filter } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../../ui/dialog';
import { Input } from '../../ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Alert, AlertDescription } from '../../ui/alert';

// 物联设备接口（来自全域数据感知中心）
interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: string;
  deviceTypeId?: string;
  manufacturer: string;
  model: string;
  location: string;
  fieldId: string;
  fieldName: string;
  protocol: string;
  ipAddress?: string;
  mqttTopic?: string;
  status: '在线' | '离线' | '故障' | '维护中';
  bindingStatus: '未绑定' | '已绑定';
  bindingSystem?: string;
  lastReportTime: string;
  dataFrequency: string;
  batteryLevel?: number;
  signalStrength?: number;
  sensors: {
    name: string;
    unit: string;
    currentValue: number;
    normalRange: string;
  }[];
}

export function LoadDeviceLibrary() {
  const [iotDevices, setIotDevices] = useState<IoTDevice[]>([]);
  const [filteredDevices, setFilteredDevices] = useState<IoTDevice[]>([]);
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [viewingDevice, setViewingDevice] = useState<IoTDevice | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');

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

  useEffect(() => {
    filterDevices();
  }, [iotDevices, searchTerm, statusFilter, typeFilter]);

  const loadData = () => {
    // 从全域数据感知中心的物联设备数据接入读取数据
    const devicesData = localStorage.getItem('smart_agriculture_iot_devices');
    if (devicesData) {
      setIotDevices(JSON.parse(devicesData));
    } else {
      // 如果没有数据，初始化示例数据
      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: 'SOIL-2024-001',
          name: '1号土壤传感器',
          type: '土壤传感器',
          deviceTypeId: 'device-type-1',
          manufacturer: '大疆',
          model: 'DJI-Soil-X1',
          location: '东区1号地中心点',
          fieldId: 'field_002',
          fieldName: '东区1号地',
          protocol: 'LoRa',
          status: '在线',
          bindingStatus: '已绑定',
          bindingSystem: '智能灌溉控制系统',
          lastReportTime: '2024-10-15 14:00:00',
          dataFrequency: '每10分钟',
          batteryLevel: 92,
          signalStrength: 88,
          sensors: [
            { name: '土壤温度', unit: '℃', currentValue: 18.5, normalRange: '-5~45' },
            { name: '土壤湿度', unit: '%', currentValue: 45, normalRange: '0~100' },
            { name: 'EC值', unit: 'mS/cm', currentValue: 1.2, normalRange: '0~5' },
            { name: 'pH值', unit: '', currentValue: 6.8, normalRange: '4~9' },
          ],
        },
        {
          id: 'iot-3',
          code: 'CAM-2024-001',
          name: '东区监控摄像头',
          type: '摄像头',
          deviceTypeId: 'device-type-3',
          manufacturer: '海康威视',
          model: 'HIK-CAM-4K',
          location: '东区入口处',
          fieldId: 'field_002',
          fieldName: '东区1号地',
          protocol: 'TCP/IP',
          ipAddress: '192.168.1.100',
          status: '在线',
          bindingStatus: '已绑定',
          bindingSystem: '智能安防系统',
          lastReportTime: '2024-10-15 14:08:00',
          dataFrequency: '实时',
          signalStrength: 95,
          sensors: [],
        },
        {
          id: 'iot-4',
          code: 'GPS-2024-001',
          name: '农机GPS定位器-01',
          type: 'GPS定位器',
          deviceTypeId: 'device-type-4',
          manufacturer: '北斗星通',
          model: 'BD-GPS-Pro',
          location: '拖拉机-001',
          fieldId: 'field_003',
          fieldName: '西区2号地',
          protocol: 'GNSS',
          status: '在线',
          bindingStatus: '已绑定',
          bindingSystem: '智能农机管理系统',
          lastReportTime: '2024-10-15 14:09:00',
          dataFrequency: '每秒',
          batteryLevel: 78,
          signalStrength: 90,
          sensors: [
            { name: '纬度', unit: '°', currentValue: 39.9042, normalRange: '-90~90' },
            { name: '经度', unit: '°', currentValue: 116.4074, normalRange: '-180~180' },
            { name: '速度', unit: 'km/h', currentValue: 12.5, normalRange: '0~100' },
          ],
        },
        {
          id: 'iot-5',
          code: 'FLOW-2024-001',
          name: '水流量计-01',
          type: '流量计',
          deviceTypeId: 'device-type-5',
          manufacturer: '艾默生',
          model: 'EMR-Flow-500',
          location: '主灌溉管道A',
          fieldId: 'field_001',
          fieldName: '1号大棚',
          protocol: 'Modbus',
          ipAddress: '192.168.1.50',
          status: '在线',
          bindingStatus: '已绑定',
          bindingSystem: '智能灌溉控制系统',
          lastReportTime: '2024-10-15 14:07:00',
          dataFrequency: '每分钟',
          signalStrength: 85,
          sensors: [
            { name: '流量', unit: 'm³/h', currentValue: 5.2, normalRange: '0~50' },
            { name: '累计流量', unit: 'm³', currentValue: 125.8, normalRange: '0~10000' },
            { name: '压力', unit: 'MPa', currentValue: 0.35, normalRange: '0~1' },
          ],
        },
        {
          id: 'iot-6',
          code: 'LIGHT-2024-001',
          name: '光照传感器-01',
          type: '光照传感器',
          deviceTypeId: 'device-type-6',
          manufacturer: '施耐德',
          model: 'SE-Light-Pro',
          location: '1号大棚顶部',
          fieldId: 'field_001',
          fieldName: '1号大棚',
          protocol: 'Zigbee',
          status: '离线',
          bindingStatus: '已绑定',
          bindingSystem: '智能温室控制系统',
          lastReportTime: '2024-10-15 12:30:00',
          dataFrequency: '每5分钟',
          batteryLevel: 15,
          signalStrength: 45,
          sensors: [
            { name: '光照强度', unit: 'lux', currentValue: 35000, normalRange: '0~100000' },
          ],
        },
      ];
      localStorage.setItem('smart_agriculture_iot_devices', JSON.stringify(mockDevices));
      setIotDevices(mockDevices);
    }
  };

  const filterDevices = () => {
    let filtered = iotDevices;

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(device =>
        device.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        device.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
        device.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
        device.manufacturer.toLowerCase().includes(searchTerm.toLowerCase()) ||
        device.model.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

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

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

    setFilteredDevices(filtered);
  };

  const handleViewDetails = (device: IoTDevice) => {
    setViewingDevice(device);
    setShowDetailsDialog(true);
  };

  const handleRefresh = () => {
    loadData();
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '在线': return 'bg-success-muted text-success';
      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 getBindingStatusColor = (status: string) => {
    return status === '已绑定'
      ? 'bg-success-muted text-success border-success'
      : 'bg-muted text-muted-foreground border-border';
  };

  const deviceTypes = [...new Set(iotDevices.map(d => d.type))];

  const stats = {
    totalDevices: iotDevices.length,
    onlineDevices: iotDevices.filter(d => d.status === '在线').length,
    offlineDevices: iotDevices.filter(d => d.status === '离线').length,
    boundDevices: iotDevices.filter(d => d.bindingStatus === '已绑定').length,
  };

  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 variant="outline" onClick={handleRefresh}>
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新数据
        </Button>
      </div>

      {/* 数据来源说明 */}
      <Alert>
        <Info className="h-4 w-4" />
        <AlertDescription>
          负载设备数据来源于"AI作物模型精准决策系统 → 全域数据感知中心 → 物联设备数据接入"。
          如需新增、编辑或删除设备，请前往该模块进行管理。
        </AlertDescription>
      </Alert>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20">
          <div className="text-sm text-muted-foreground">设备总数</div>
          <div className="mt-1 text-info">{stats.totalDevices}</div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20">
          <div className="text-sm text-muted-foreground">在线设备</div>
          <div className="mt-1 text-success">{stats.onlineDevices}</div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-800/20 dark:to-gray-700/20">
          <div className="text-sm text-muted-foreground">离线设备</div>
          <div className="mt-1 text-gray-600 dark:text-gray-400">{stats.offlineDevices}</div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20">
          <div className="text-sm text-muted-foreground">已绑定设备</div>
          <div className="mt-1 text-info">{stats.boundDevices}</div>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <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={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <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>
              <SelectValue placeholder="按类型筛选" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              {deviceTypes.map(type => (
                <SelectItem key={type} value={type}>{type}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 设备列表 */}
      <Card>
        <div className="p-4 border-b">
          <h3>设备列表</h3>
          <p className="text-sm text-muted-foreground">共 {filteredDevices.length} 个设备</p>
        </div>
        
        {filteredDevices.length === 0 ? (
          <div className="text-center text-muted-foreground py-12">
            <Filter className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p>暂无符合条件的设备</p>
          </div>
        ) : (
          <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>
                  <TableHead>最后上报</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredDevices.map((device) => (
                  <TableRow key={device.id}>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">
                        {device.code}
                      </code>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div>{device.name}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.type}</Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div className="text-sm">{device.manufacturer}</div>
                        <div className="text-xs text-muted-foreground">{device.model}</div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="bg-success-muted text-success border-success">
                        {device.fieldName}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm">{device.location}</TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        <Badge className={getBindingStatusColor(device.bindingStatus)}>
                          {device.bindingStatus}
                        </Badge>
                        {device.bindingSystem && (
                          <span className="text-xs text-muted-foreground">{device.bindingSystem}</span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.protocol}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(device.status)}>
                        {device.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        {device.signalStrength !== undefined && (
                          <div>信号: {device.signalStrength}%</div>
                        )}
                        {device.batteryLevel !== undefined && (
                          <div>电量: {device.batteryLevel}%</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-sm">
                      {device.lastReportTime}
                    </TableCell>
                    <TableCell className="text-right">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetails(device)}
                        title="查看详情"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </Card>

      {/* 设备详情对话框 */}
      <Dialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>设备详情</DialogTitle>
            <DialogDescription>查看物联设备的详细配置信息</DialogDescription>
          </DialogHeader>
          
          {viewingDevice && (
            <div className="space-y-6">
              {/* 基础信息 */}
              <div>
                <h4 className="mb-3">基础信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>设备编号</Label>
                    <div className="field-value">
                      <code className="text-sm">{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">{viewingDevice.manufacturer}</div>
                  </div>
                  <div>
                    <Label>型号</Label>
                    <div className="field-value">{viewingDevice.model}</div>
                  </div>
                  <div>
                    <Label>设备状态</Label>
                    <div className="field-value">
                      <Badge className={getStatusColor(viewingDevice.status)}>
                        {viewingDevice.status}
                      </Badge>
                    </div>
                  </div>
                </div>
              </div>

              {/* 位置信息 */}
              <div>
                <h4 className="mb-3">位置信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>所属地块</Label>
                    <div className="field-value">
                      <Badge variant="outline" className="bg-success-muted text-success border-success">
                        {viewingDevice.fieldName}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>具体位置</Label>
                    <div className="field-value">{viewingDevice.location}</div>
                  </div>
                </div>
              </div>

              {/* 通信信息 */}
              <div>
                <h4 className="mb-3">通信信息</h4>
                <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-sm">{viewingDevice.ipAddress}</code>
                      </div>
                    </div>
                  )}
                  {viewingDevice.mqttTopic && (
                    <div>
                      <Label>MQTT主题</Label>
                      <div className="field-value">
                        <code className="text-sm">{viewingDevice.mqttTopic}</code>
                      </div>
                    </div>
                  )}
                  <div>
                    <Label>数据频率</Label>
                    <div className="field-value">{viewingDevice.dataFrequency}</div>
                  </div>
                  <div>
                    <Label>最后上报时间</Label>
                    <div className="field-value">{viewingDevice.lastReportTime}</div>
                  </div>
                  {viewingDevice.signalStrength !== undefined && (
                    <div>
                      <Label>信号强度</Label>
                      <div className="field-value">{viewingDevice.signalStrength}%</div>
                    </div>
                  )}
                  {viewingDevice.batteryLevel !== undefined && (
                    <div>
                      <Label>电池电量</Label>
                      <div className="field-value">{viewingDevice.batteryLevel}%</div>
                    </div>
                  )}
                </div>
              </div>

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

              {/* 传感器信息 */}
              {viewingDevice.sensors.length > 0 && (
                <div>
                  <h4 className="mb-3">传感器数据</h4>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>传感器名称</TableHead>
                        <TableHead>当前值</TableHead>
                        <TableHead>单位</TableHead>
                        <TableHead>正常范围</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {viewingDevice.sensors.map((sensor, idx) => (
                        <TableRow key={idx}>
                          <TableCell>{sensor.name}</TableCell>
                          <TableCell className="font-medium">{sensor.currentValue}</TableCell>
                          <TableCell>{sensor.unit}</TableCell>
                          <TableCell className="text-muted-foreground">{sensor.normalRange}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

// Label组件
function Label({ children, className = '' }: { children: React.ReactNode; className?: string }) {
  return (
    <label className={`text-sm font-semibold text-muted-foreground uppercase tracking-wide ${className}`}>
      {children}
    </label>
  );
}
