import { useState } 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,
  Download,
  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;
}

// 可选择的设备类型库
const deviceLibrary = [
  { id: 'type-1', name: '综合环境监测站', sensors: ['temperature', 'humidity', 'co2', 'light', 'pm25'] },
  { id: 'type-2', name: '气象传感器', sensors: ['temperature', 'humidity', 'light'] },
  { id: 'type-3', name: 'CO2监测器', sensors: ['temperature', 'humidity', 'co2'] },
  { id: 'type-4', name: '空气质量监测仪', sensors: ['temperature', 'humidity', 'pm25'] },
  { id: 'type-5', name: '光照传感器', sensors: ['light'] },
];

// 可选择的地块
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 [deviceForm, setDeviceForm] = useState({
    name: '',
    type: '',
    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 },
  ];

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

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'offline': return 'bg-gray-500';
      case 'warning': return 'bg-yellow-500';
      default: return 'bg-gray-500';
    }
  };

  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-green-600' };
    if (co2 < 600) return { label: '良好', color: 'text-blue-600' };
    if (co2 < 1000) return { label: '偏高', color: 'text-yellow-600' };
    return { label: '过高', color: 'text-red-600' };
  };

  const getPM25Level = (pm25: number) => {
    if (pm25 < 35) return { label: '优', color: 'text-green-600' };
    if (pm25 < 75) return { label: '良', color: 'text-blue-600' };
    if (pm25 < 115) return { label: '轻度污染', color: 'text-yellow-600' };
    return { label: '重度污染', color: 'text-red-600' };
  };

  const handleExportData = () => {
    toast.success('环境监测数据已导出为Excel格式');
  };

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

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

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

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

    const field = availableFields.find(f => f.id === deviceForm.fieldId);
    if (!field) {
      toast.error('无效的地块');
      return;
    }

    if (editingDevice) {
      // 编辑设备
      setSensorDevices(devices =>
        devices.map(d =>
          d.id === editingDevice.id
            ? {
                ...d,
                name: deviceForm.name,
                type: deviceForm.type,
                location: deviceForm.location,
                fieldId: deviceForm.fieldId,
                fieldName: field.name,
              }
            : d
        )
      );
      toast.success('设备信息已更新');
    } else {
      // 添加新设备
      const newDevice: SensorDevice = {
        id: `device-${Date.now()}`,
        name: deviceForm.name,
        type: deviceForm.type,
        location: deviceForm.location,
        fieldId: deviceForm.fieldId,
        fieldName: field.name,
        status: 'online',
        battery: 100,
        lastUpdate: new Date().toLocaleString('zh-CN'),
        sensors: {
          temperature: 22,
          humidity: 60,
          co2: 400,
          light: 40000,
          pm25: 30,
        },
      };
      setSensorDevices([...sensorDevices, newDevice]);
      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-green-800">环境监测</h2>
          <p className="text-muted-foreground">
            物联网传感器管理、环境数据采集与分析
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExportData}>
            <Download className="w-4 h-4 mr-2" />
            导出数据
          </Button>
          <Button className="bg-green-600 hover:bg-green-700" 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-green-600">{onlineDevices}</p>
            </div>
            <CheckCircle2 className="w-10 h-10 text-green-600 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-yellow-600">{warningDevices}</p>
            </div>
            <AlertCircle className="w-10 h-10 text-yellow-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>
            <Radio className="w-10 h-10 text-gray-600 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-blue-600">{sensorDevices.length}</p>
            </div>
            <Activity className="w-10 h-10 text-blue-600 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-red-600" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">空气温度</p>
            <p className="mt-2 text-2xl text-red-600">{currentDevice.sensors.temperature}°C</p>
            <p className="text-xs text-green-600 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-blue-600" />
              <Badge variant="outline">实时</Badge>
            </div>
            <p className="text-xs text-muted-foreground">空气湿度</p>
            <p className="mt-2 text-2xl text-blue-600">{currentDevice.sensors.humidity}%</p>
            <p className="text-xs text-red-600 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(1)}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>
      </Card>

      <Tabs defaultValue="devices">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="devices">设备管理</TabsTrigger>
          <TabsTrigger value="realtime">实时数据</TabsTrigger>
          <TabsTrigger value="history">历史数据</TabsTrigger>
        </TabsList>

        {/* 设备管理 */}
        <TabsContent value="devices" className="space-y-4">
          <div className="space-y-3">
            {sensorDevices.map((device) => (
              <Card key={device.id} className="p-4">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-3">
                      <Radio className="w-5 h-5 text-green-600" />
                      <div>
                        <div className="flex items-center gap-2">
                          <h4>{device.name}</h4>
                          <Badge className={`${getStatusColor(device.status)} text-white`}>
                            {getStatusLabel(device.status)}
                          </Badge>
                          <Badge variant="outline">{device.type}</Badge>
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                          {device.fieldName} · {device.location}
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-6 gap-4 pl-8">
                      <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">{device.sensors.temperature}°C</p>
                        </div>
                      </div>
                      <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">{device.sensors.humidity}%</p>
                        </div>
                      </div>
                      <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">{device.sensors.co2} ppm</p>
                        </div>
                      </div>
                      <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">{(device.sensors.light! / 1000).toFixed(0)}k lux</p>
                        </div>
                      </div>
                      <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">{device.sensors.pm25} μg/m³</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Battery className="w-4 h-4 text-gray-600" />
                        <div>
                          <p className="text-xs text-muted-foreground">电量</p>
                          <p className={`text-sm font-medium ${device.battery < 40 ? 'text-red-600' : ''}`}>
                            {device.battery}%
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="mt-3 pl-8 text-xs text-muted-foreground">
                      最后更新: {device.lastUpdate}
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => handleViewDevice(device)}>
                      <Eye className="w-4 h-4 mr-1" />
                      查看
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => handleEditDevice(device)}>
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => handleDeleteDevice(device.id)}>
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 实时数据 */}
        <TabsContent value="realtime" className="space-y-4">
          <Card className="p-4">
            <div className="flex items-center gap-4 mb-4">
              <div className="flex-1">
                <label className="text-xs text-muted-foreground mb-2 block">选择设备</label>
                <Select value={selectedDevice} onValueChange={setSelectedDevice}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {sensorDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        {device.name} - {device.fieldName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="flex-1">
                <label className="text-xs text-muted-foreground mb-2 block">时间范围</label>
                <div className="flex gap-2">
                  {(['1h', '6h', '24h', '7d'] as const).map((range) => (
                    <Button
                      key={range}
                      variant={timeRange === range ? 'default' : 'outline'}
                      size="sm"
                      onClick={() => setTimeRange(range)}
                      className="flex-1"
                    >
                      {range === '1h' ? '1小时' : range === '6h' ? '6小时' : range === '24h' ? '24小时' : '7天'}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          </Card>

          <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>

            <Card className="p-6">
              <h3 className="mb-4">PM2.5浓度</h3>
              <ResponsiveContainer width="100%" height={220}>
                <BarChart 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: 'PM2.5 (μg/m³)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} μg/m³`, 'PM2.5']}
                  />
                  <Bar 
                    dataKey="pm25" 
                    fill="#a855f7" 
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 历史数据 */}
        <TabsContent value="history" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">历史环境数据查询</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">时间</th>
                    <th className="px-4 py-3 text-center text-xs">温度(°C)</th>
                    <th className="px-4 py-3 text-center text-xs">湿度(%)</th>
                    <th className="px-4 py-3 text-center text-xs">CO₂(ppm)</th>
                    <th className="px-4 py-3 text-center text-xs">光照(lux)</th>
                    <th className="px-4 py-3 text-center text-xs">PM2.5(μg/m³)</th>
                    <th className="px-4 py-3 text-center text-xs">评价</th>
                  </tr>
                </thead>
                <tbody>
                  {environmentData.map((data, index) => (
                    <tr key={index} className="border-t hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm">2024-10-18 {data.time}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.temperature}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.humidity}</td>
                      <td className="px-4 py-3 text-center text-sm">
                        <span className={getCO2Level(data.co2).color}>{data.co2}</span>
                      </td>
                      <td className="px-4 py-3 text-center text-sm">{data.light}</td>
                      <td className="px-4 py-3 text-center text-sm">
                        <span className={getPM25Level(data.pm25).color}>{data.pm25}</span>
                      </td>
                      <td className="px-4 py-3 text-center text-sm">
                        <Badge className="bg-green-500">良好</Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </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">
            <div>
              <Label>设备名称</Label>
              <Input
                value={deviceForm.name}
                onChange={(e) => setDeviceForm({ ...deviceForm, name: e.target.value })}
                placeholder="如：ENV-004"
              />
            </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>
              <Select value={deviceForm.type} onValueChange={(value) => setDeviceForm({ ...deviceForm, type: value })}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择设备类型" />
                </SelectTrigger>
                <SelectContent>
                  {deviceLibrary.map((device) => (
                    <SelectItem key={device.id} value={device.name}>
                      {device.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>
  );
}
