import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Label } from '../ui/label';
import {
  Thermometer,
  Droplets,
  Wind,
  Leaf,
  Eye,
  Plus,
  Edit,
  Trash2,
  Activity,
  TrendingUp,
  AlertCircle,
  CheckCircle2,
  Radio,
  Wifi,
  Battery,
  X,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';

interface SensorDevice {
  id: string;
  name: string;
  type: string;
  location: string;
  fieldId: string;
  fieldName: string;
  status: 'online' | 'offline' | 'warning';
  battery: number;
  lastUpdate: string;
  sensors: {
    temperature?: number;
    humidity?: number;
    co2?: number;
    light?: number;
    pm25?: number;
  };
}

interface EnvironmentData {
  time: string;
  temperature: number;
  humidity: number;
  co2: number;
  light: number;
  pm25: number;
}

// 从AI数据中心获取的物联设备接口
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: string;
  bindingStatus: '未绑定' | '已绑定';
  bindingSystem?: string;
  lastReportTime: string;
  dataFrequency: string;
  batteryLevel?: number;
  signalStrength?: number;
  sensors: {
    name: string;
    unit: string;
    currentValue: number;
    normalRange: string;
  }[];
}

// 可选择的地块
const availableFields = [
  { id: 'field-1', name: '东区1号地' },
  { id: 'field-2', name: '西区2号地' },
  { id: 'field-3', name: '南区3号地' },
  { id: 'field-4', name: '北区4号地' },
];

export function EnvironmentMonitoring() {
  const [selectedDevice, setSelectedDevice] = useState('device-1');
  const [showDeviceDialog, setShowDeviceDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [editingDevice, setEditingDevice] = useState<SensorDevice | null>(null);
  const [viewingDevice, setViewingDevice] = useState<SensorDevice | null>(null);
  const [timeRange, setTimeRange] = useState<'1h' | '6h' | '24h' | '7d'>('24h');
  const [availableIoTDevices, setAvailableIoTDevices] = useState<IoTDevice[]>([]);

  // 设备表单
  const [deviceForm, setDeviceForm] = useState({
    iotDeviceId: '', // 选择的物联设备ID
    location: '',
    fieldId: '',
  });

  // 模拟传感器设备列表
  const [sensorDevices, setSensorDevices] = useState<SensorDevice[]>([
    {
      id: 'device-1',
      name: 'ENV-001',
      type: '综合环境监测站',
      location: '东区1号地中心',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      status: 'online',
      battery: 85,
      lastUpdate: '2024-10-18 15:30',
      sensors: {
        temperature: 24.5,
        humidity: 62,
        co2: 420,
        light: 45000,
        pm25: 35,
      },
    },
    {
      id: 'device-2',
      name: 'ENV-002',
      type: '气象传感器',
      location: '西区2号地北侧',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      status: 'online',
      battery: 92,
      lastUpdate: '2024-10-18 15:28',
      sensors: {
        temperature: 23.8,
        humidity: 68,
        co2: 410,
        light: 42000,
        pm25: 28,
      },
    },
    {
      id: 'device-3',
      name: 'ENV-003',
      type: 'CO2监测器',
      location: '南区3号地温室',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      status: 'warning',
      battery: 35,
      lastUpdate: '2024-10-18 15:25',
      sensors: {
        temperature: 26.2,
        humidity: 75,
        co2: 550,
        light: 38000,
        pm25: 42,
      },
    },
  ]);

  // 模拟环境数据
  const environmentData: EnvironmentData[] = [
    { time: '00:00', temperature: 18, humidity: 75, co2: 380, light: 0, pm25: 25 },
    { time: '03:00', temperature: 16, humidity: 80, co2: 390, light: 0, pm25: 22 },
    { time: '06:00', temperature: 15, humidity: 85, co2: 400, light: 5000, pm25: 20 },
    { time: '09:00', temperature: 20, humidity: 70, co2: 410, light: 35000, pm25: 28 },
    { time: '12:00', temperature: 25, humidity: 55, co2: 420, light: 50000, pm25: 35 },
    { time: '15:00', temperature: 24.5, humidity: 62, co2: 420, light: 45000, pm25: 35 },
    { time: '18:00', temperature: 22, humidity: 65, co2: 410, light: 15000, pm25: 30 },
    { time: '21:00', temperature: 19, humidity: 72, co2: 395, light: 0, pm25: 26 },
  ];

  // 从AI数据中心加载物联设备
  useEffect(() => {
    const loadIoTDevices = () => {
      const data = localStorage.getItem('smart_agriculture_ai_iot_devices');
      if (data) {
        const devices: IoTDevice[] = JSON.parse(data);
        // 只显示环境监测站类型且未绑定的设备
        const environmentDevices = devices.filter(
          d => d.type === '环境监测站' && d.bindingStatus === '未绑定'
        );
        setAvailableIoTDevices(environmentDevices);
      }
    };
    loadIoTDevices();
  }, [showDeviceDialog]);

  const currentDevice = sensorDevices.find(d => d.id === selectedDevice) || sensorDevices[0];

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-success';
      case 'offline': return 'bg-muted-foreground';
      case 'warning': return 'bg-warning';
      default: return 'bg-muted-foreground';
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'online': return '在线';
      case 'offline': return '离线';
      case 'warning': return '警告';
      default: return '未知';
    }
  };

  const getCO2Level = (co2: number) => {
    if (co2 < 400) return { label: '正常', color: 'text-success' };
    if (co2 < 600) return { label: '良好', color: 'text-info' };
    if (co2 < 1000) return { label: '偏高', color: 'text-warning' };
    return { label: '过高', color: 'text-error' };
  };

  const getPM25Level = (pm25: number) => {
    if (pm25 < 35) return { label: '优', color: 'text-success' };
    if (pm25 < 75) return { label: '良', color: 'text-info' };
    if (pm25 < 115) return { label: '轻度污染', color: 'text-warning' };
    return { label: '重度污染', color: 'text-error' };
  };

  // 打开添加设备对话框
  const handleAddDevice = () => {
    setEditingDevice(null);
    setDeviceForm({
      iotDeviceId: '',
      location: '',
      fieldId: '',
    });
    setShowDeviceDialog(true);
  };

  // 打开编辑设备对话框
  const handleEditDevice = (device: SensorDevice) => {
    setEditingDevice(device);
    setDeviceForm({
      iotDeviceId: '',
      location: device.location,
      fieldId: device.fieldId,
    });
    setShowDeviceDialog(true);
  };

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

  // 保存设备
  const handleSaveDevice = () => {
    if (!deviceForm.iotDeviceId || !deviceForm.fieldId) {
      toast.error('请填写完整信息');
      return;
    }

    const field = availableFields.find(f => f.id === deviceForm.fieldId);
    const iotDevice = availableIoTDevices.find(d => d.id === deviceForm.iotDeviceId);
    
    if (!field || !iotDevice) {
      toast.error('无效的选择');
      return;
    }

    if (editingDevice) {
      // 编辑设备
      setSensorDevices(devices =>
        devices.map(d =>
          d.id === editingDevice.id
            ? {
                ...d,
                location: deviceForm.location,
                fieldId: deviceForm.fieldId,
                fieldName: field.name,
              }
            : d
        )
      );
      toast.success('设备信息已更新');
    } else {
      // 添加新设备
      const newDevice: SensorDevice = {
        id: `device-${Date.now()}`,
        name: iotDevice.code,
        type: iotDevice.type,
        location: deviceForm.location,
        fieldId: deviceForm.fieldId,
        fieldName: field.name,
        status: 'online',
        battery: iotDevice.batteryLevel || 100,
        lastUpdate: new Date().toLocaleString('zh-CN'),
        sensors: {
          temperature: 22,
          humidity: 60,
          co2: 400,
          light: 40000,
          pm25: 30,
        },
      };
      setSensorDevices([...sensorDevices, newDevice]);

      // 更新AI数据中心的设备绑定状态
      const allIoTDevices = localStorage.getItem('smart_agriculture_ai_iot_devices');
      if (allIoTDevices) {
        const devices: IoTDevice[] = JSON.parse(allIoTDevices);
        const updatedDevices = devices.map(d =>
          d.id === deviceForm.iotDeviceId
            ? { ...d, bindingStatus: '已绑定' as const, bindingSystem: '地块环境监测-环境监测' }
            : d
        );
        localStorage.setItem('smart_agriculture_ai_iot_devices', JSON.stringify(updatedDevices));
      }

      toast.success('设备添加成功');
    }

    setShowDeviceDialog(false);
  };

  // 删除设备
  const handleDeleteDevice = (deviceId: string) => {
    if (confirm('确定要删除该设备吗？')) {
      setSensorDevices(devices => devices.filter(d => d.id !== deviceId));
      toast.success('设备已删除');
    }
  };

  // 统计数据
  const onlineDevices = sensorDevices.filter(d => d.status === 'online').length;
  const warningDevices = sensorDevices.filter(d => d.status === 'warning').length;
  const offlineDevices = sensorDevices.filter(d => d.status === 'offline').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">环境监测</h2>
          <p className="text-muted-foreground">
            物联网传感器管理、环境数据采集与分析
          </p>
        </div>
        <div className="flex gap-2">
          <Button className="bg-success hover:bg-success/90" onClick={handleAddDevice}>
            <Plus className="w-4 h-4 mr-2" />
            添加设备
          </Button>
        </div>
      </div>

      {/* 设备状态总览 */}
      <div className="grid grid-cols-4 gap-4">
        <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-success">{onlineDevices}</p>
            </div>
            <CheckCircle2 className="w-10 h-10 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-yellow-50 to-yellow-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">警告设备</p>
              <p className="mt-2 text-2xl text-warning">{warningDevices}</p>
            </div>
            <AlertCircle className="w-10 h-10 text-warning 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-muted-foreground">{offlineDevices}</p>
            </div>
            <Radio className="w-10 h-10 text-muted-foreground opacity-50" />
          </div>
        </Card>

        <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-info">{sensorDevices.length}</p>
            </div>
            <Activity className="w-10 h-10 text-info opacity-50" />
          </div>
        </Card>
      </div>

      {/* 设备选择和实时监测数据 */}
      <Card className="p-4">
        <div className="flex items-center gap-4 mb-4">
          <Label className="text-sm">选择设备查看实时数据:</Label>
          <Select value={selectedDevice} onValueChange={setSelectedDevice}>
            <SelectTrigger className="w-80">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {sensorDevices.map((device) => (
                <SelectItem key={device.id} value={device.id}>
                  {device.name} - {device.fieldName} - {device.type}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Badge variant="outline" className={`${getStatusColor(currentDevice.status)} text-white`}>
            {getStatusLabel(currentDevice.status)}
          </Badge>
          <Badge variant="outline">
            电量: {currentDevice.battery}%
          </Badge>
        </div>

        <div className="grid grid-cols-5 gap-4">
          <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100">
            <div className="flex items-center justify-between mb-2">
              <Thermometer className="w-6 h-6 text-error" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">空气温度</p>
            <p className="mt-2 text-2xl text-error">{currentDevice.sensors.temperature}°C</p>
            <p className="text-xs text-success mt-1">↑ 0.5°C</p>
          </Card>

          <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
            <div className="flex items-center justify-between mb-2">
              <Droplets className="w-6 h-6 text-info" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">空气湿度</p>
            <p className="mt-2 text-2xl text-info">{currentDevice.sensors.humidity}%</p>
            <p className="text-xs text-error mt-1">↓ 3%</p>
          </Card>

          <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
            <div className="flex items-center justify-between mb-2">
              <Leaf className="w-6 h-6 text-green-600" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">CO₂浓度</p>
            <p className="mt-2 text-2xl text-green-600">{currentDevice.sensors.co2}</p>
            <p className="text-xs text-muted-foreground mt-1">ppm</p>
          </Card>

          <Card className="p-4 bg-gradient-to-br from-yellow-50 to-yellow-100">
            <div className="flex items-center justify-between mb-2">
              <Eye className="w-6 h-6 text-yellow-600" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">光照强度</p>
            <p className="mt-2 text-2xl text-yellow-600">{(currentDevice.sensors.light! / 1000).toFixed(0)}k</p>
            <p className="text-xs text-muted-foreground mt-1">lux</p>
          </Card>

          <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
            <div className="flex items-center justify-between mb-2">
              <Wind className="w-6 h-6 text-purple-600" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">PM2.5</p>
            <p className="mt-2 text-2xl text-purple-600">{currentDevice.sensors.pm25}</p>
            <p className="text-xs text-muted-foreground mt-1">μg/m³</p>
          </Card>
        </div>

        <div className="mt-4 grid grid-cols-2 gap-4">
          <Card className="p-4 bg-gradient-to-br from-green-50 to-white">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">CO₂水平评估</p>
                <p className={`mt-2 ${getCO2Level(currentDevice.sensors.co2!).color}`}>
                  {getCO2Level(currentDevice.sensors.co2!).label}
                </p>
              </div>
              <TrendingUp className="w-8 h-8 text-green-600 opacity-30" />
            </div>
          </Card>

          <Card className="p-4 bg-gradient-to-br from-purple-50 to-white">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">空气质量评估</p>
                <p className={`mt-2 ${getPM25Level(currentDevice.sensors.pm25!).color}`}>
                  {getPM25Level(currentDevice.sensors.pm25!).label}
                </p>
              </div>
              <Wind className="w-8 h-8 text-purple-600 opacity-30" />
            </div>
          </Card>
        </div>
      </Card>

      {/* 设备列表和数据趋势 */}
      <Tabs defaultValue="devices" className="w-full">
        <TabsList>
          <TabsTrigger value="devices">设备管理</TabsTrigger>
          <TabsTrigger value="trends">数据趋势</TabsTrigger>
        </TabsList>

        <TabsContent value="devices">
          <Card className="p-4">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-2">设备名称</th>
                    <th className="text-left p-2">类型</th>
                    <th className="text-left p-2">地块</th>
                    <th className="text-left p-2">位置</th>
                    <th className="text-left p-2">状态</th>
                    <th className="text-left p-2">电量</th>
                    <th className="text-left p-2">最后更新</th>
                    <th className="text-left p-2">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {sensorDevices.map((device) => (
                    <tr key={device.id} className="border-b hover:bg-gray-50">
                      <td className="p-2">{device.name}</td>
                      <td className="p-2">{device.type}</td>
                      <td className="p-2">{device.fieldName}</td>
                      <td className="p-2">{device.location}</td>
                      <td className="p-2">
                        <Badge variant="outline" className={`${getStatusColor(device.status)} text-white`}>
                          {getStatusLabel(device.status)}
                        </Badge>
                      </td>
                      <td className="p-2">
                        <div className="flex items-center gap-1">
                          <Battery className={`w-4 h-4 ${device.battery < 40 ? 'text-red-500' : 'text-green-500'}`} />
                          <span className={device.battery < 40 ? 'text-red-600' : ''}>
                            {device.battery}%
                          </span>
                        </div>
                      </td>
                      <td className="p-2 text-sm text-muted-foreground">{device.lastUpdate}</td>
                      <td className="p-2">
                        <div className="flex gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewDevice(device)}
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditDevice(device)}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteDevice(device.id)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>

        <TabsContent value="trends">
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4">温度变化曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={environmentData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '温度 (°C)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value}°C`, '温度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="temperature" 
                    stroke="#dc2626" 
                    strokeWidth={2}
                    dot={{ fill: '#dc2626', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">湿度变化曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={environmentData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '湿度 (%)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value}%`, '湿度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="humidity" 
                    stroke="#2563eb" 
                    strokeWidth={2}
                    dot={{ fill: '#2563eb', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">CO₂浓度曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={environmentData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: 'CO₂ (ppm)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} ppm`, 'CO₂浓度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="co2" 
                    stroke="#22c55e" 
                    strokeWidth={2}
                    dot={{ fill: '#22c55e', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">光照强度曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={environmentData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '光照 (lux)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} lux`, '光照强度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="light" 
                    stroke="#eab308" 
                    strokeWidth={2}
                    dot={{ fill: '#eab308', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 添加/编辑设备对话框 */}
      <Dialog open={showDeviceDialog} onOpenChange={setShowDeviceDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{editingDevice ? '编辑设备' : '添加设备'}</DialogTitle>
            <DialogDescription>
              {editingDevice ? '修改设备信息' : '从物联设备数据接入中选择设备并配置'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {!editingDevice && (
              <div>
                <Label>选择设备</Label>
                <Select value={deviceForm.iotDeviceId} onValueChange={(value) => setDeviceForm({ ...deviceForm, iotDeviceId: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="请从物联设备数据接入中选择" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableIoTDevices.length === 0 ? (
                      <div className="p-4 text-sm text-muted-foreground text-center">
                        暂无可用设备<br/>
                        请先在AI系统-全域数据感知中心-物联设备数据接入中添加环境监测站设备
                      </div>
                    ) : (
                      availableIoTDevices.map((device) => (
                        <SelectItem key={device.id} value={device.id}>
                          {device.code} - {device.name} ({device.manufacturer} {device.model})
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
              </div>
            )}

            <div>
              <Label>选择地块</Label>
              <Select value={deviceForm.fieldId} onValueChange={(value) => setDeviceForm({ ...deviceForm, fieldId: value })}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择地块" />
                </SelectTrigger>
                <SelectContent>
                  {availableFields.map((field) => (
                    <SelectItem key={field.id} value={field.id}>
                      {field.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>安装位置</Label>
              <Input
                value={deviceForm.location}
                onChange={(e) => setDeviceForm({ ...deviceForm, location: e.target.value })}
                placeholder="如：地块中心位置"
              />
            </div>

            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button variant="outline" onClick={() => setShowDeviceDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveDevice}>
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 查看设备详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>设备详情</DialogTitle>
            <DialogDescription>
              {viewingDevice?.name} - {viewingDevice?.type}
            </DialogDescription>
          </DialogHeader>
          {viewingDevice && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>设备名称</Label>
                  <div className="field-value">{viewingDevice.name}</div>
                </div>
                <div>
                  <Label>设备类型</Label>
                  <div className="field-value">{viewingDevice.type}</div>
                </div>
                <div>
                  <Label>所属地块</Label>
                  <div className="field-value">{viewingDevice.fieldName}</div>
                </div>
                <div>
                  <Label>安装位置</Label>
                  <div className="field-value">{viewingDevice.location}</div>
                </div>
                <div>
                  <Label>设备状态</Label>
                  <div className="field-value">
                    <Badge className={`${getStatusColor(viewingDevice.status)} text-white`}>
                      {getStatusLabel(viewingDevice.status)}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>电池电量</Label>
                  <div className="field-value">
                    <span className={viewingDevice.battery < 40 ? 'text-red-600' : ''}>
                      {viewingDevice.battery}%
                    </span>
                  </div>
                </div>
                <div className="col-span-2">
                  <Label>最后更新时间</Label>
                  <div className="field-value">{viewingDevice.lastUpdate}</div>
                </div>
              </div>

              <div>
                <Label>传感器数据</Label>
                <div className="grid grid-cols-3 gap-3 mt-2">
                  {viewingDevice.sensors.temperature && (
                    <Card className="p-3 bg-red-50">
                      <div className="flex items-center gap-2">
                        <Thermometer className="w-4 h-4 text-red-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">温度</p>
                          <p className="text-sm font-medium">{viewingDevice.sensors.temperature}°C</p>
                        </div>
                      </div>
                    </Card>
                  )}
                  {viewingDevice.sensors.humidity && (
                    <Card className="p-3 bg-blue-50">
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-blue-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">湿度</p>
                          <p className="text-sm font-medium">{viewingDevice.sensors.humidity}%</p>
                        </div>
                      </div>
                    </Card>
                  )}
                  {viewingDevice.sensors.co2 && (
                    <Card className="p-3 bg-green-50">
                      <div className="flex items-center gap-2">
                        <Leaf className="w-4 h-4 text-green-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">CO₂</p>
                          <p className="text-sm font-medium">{viewingDevice.sensors.co2} ppm</p>
                        </div>
                      </div>
                    </Card>
                  )}
                  {viewingDevice.sensors.light && (
                    <Card className="p-3 bg-yellow-50">
                      <div className="flex items-center gap-2">
                        <Eye className="w-4 h-4 text-yellow-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">光照</p>
                          <p className="text-sm font-medium">{(viewingDevice.sensors.light / 1000).toFixed(1)}k lux</p>
                        </div>
                      </div>
                    </Card>
                  )}
                  {viewingDevice.sensors.pm25 && (
                    <Card className="p-3 bg-purple-50">
                      <div className="flex items-center gap-2">
                        <Wind className="w-4 h-4 text-purple-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">PM2.5</p>
                          <p className="text-sm font-medium">{viewingDevice.sensors.pm25} μg/m³</p>
                        </div>
                      </div>
                    </Card>
                  )}
                </div>
              </div>

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