import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import {
  Search,
  Plus,
  Edit,
  Eye,
  Trash2,
  Server,
  Wifi,
  MapPin,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Info,
  Activity,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

type DeviceStatus = '正常' | '停用';
type ProtocolType = 'Modbus-RTU' | 'Modbus-TCP' | 'HTTP' | 'MQTT' | 'OPC-UA';

// 地块数据接口
interface FieldData {
  id: string;
  code: string;
  name: string;
  area: number;
  cropType?: string;
}

interface WFDevice {
  id: string;
  deviceNo: string;
  deviceName: string;
  model: string;
  manufacturer: string;
  status: DeviceStatus;
  fieldName: string;
  fieldCode: string;
  location: string;
  installDate: string;
  ipAddress?: string;
  port?: number;
  protocol: ProtocolType;
  lastOnlineTime: string;
  workingHours: number;
  contact?: string;
  contactPhone?: string;
  notes?: string;
}

export function WaterFertilizerDevice() {
  // 地块数据（从地块管理获取）
  const [fieldsList] = useState<FieldData[]>([
    { id: 'field_001', code: 'F-001', name: '1号温室大棚', area: 2.5, cropType: '番茄' },
    { id: 'field_002', code: 'F-002', name: '2号露天田块', area: 3.0, cropType: '黄瓜' },
    { id: 'field_003', code: 'F-003', name: '3号田块', area: 5.0, cropType: '小麦' },
    { id: 'field_004', code: 'F-004', name: '4号智能温室', area: 4.2, cropType: '西红柿' },
    { id: 'field_005', code: 'F-005', name: '5号苹果园', area: 8.0, cropType: '苹果' },
    { id: 'field_006', code: 'F-006', name: '6号葡萄园', area: 6.5, cropType: '葡萄' },
    { id: 'field_007', code: 'F-007', name: '7号蔬菜大棚', area: 2.8, cropType: '茄子' },
    { id: 'field_008', code: 'F-008', name: '8号露天田块', area: 7.2, cropType: '玉米' },
  ]);

  const [devices, setDevices] = useState<WFDevice[]>([
    {
      id: 'wfd-1',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      model: 'SF-3000Pro',
      manufacturer: '智农科技',
      status: '正常',
      fieldName: '1号温室大棚',
      fieldCode: 'F-001',
      location: '大棚东南角控制柜',
      installDate: '2024-03-15',
      ipAddress: '192.168.1.101',
      port: 502,
      protocol: 'Modbus-TCP',
      lastOnlineTime: '2024-10-23 14:30:25',
      workingHours: 2580,
      contact: '张三',
      contactPhone: '13800138001',
      notes: '主力设备，性能稳定，定期维护',
    },
    {
      id: 'wfd-2',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      model: 'SF-2000',
      manufacturer: '农智通',
      status: '正常',
      fieldName: '2号露天田块',
      fieldCode: 'F-002',
      location: '田块中央灌溉站',
      installDate: '2024-05-20',
      ipAddress: '192.168.1.102',
      port: 502,
      protocol: 'Modbus-TCP',
      lastOnlineTime: '2024-10-23 14:28:10',
      workingHours: 1850,
      contact: '李四',
      contactPhone: '13800138002',
    },
    {
      id: 'wfd-3',
      deviceNo: 'WF-2024-003',
      deviceName: '3号田块水肥一体机',
      model: 'SF-3000Pro',
      manufacturer: '智农科技',
      status: '停用',
      fieldName: '3号田块',
      fieldCode: 'F-003',
      location: '田块北侧配电房',
      installDate: '2024-06-10',
      ipAddress: '192.168.1.103',
      port: 502,
      protocol: 'Modbus-TCP',
      lastOnlineTime: '2024-10-23 10:45:00',
      workingHours: 1420,
      contact: '王五',
      contactPhone: '13800138003',
      notes: '设备已停用，待升级改造',
    },
    {
      id: 'wfd-4',
      deviceNo: 'WF-2024-004',
      deviceName: '4号大棚精准水肥机',
      model: 'SF-4000Elite',
      manufacturer: '绿源智控',
      status: '正常',
      fieldName: '4号智能温室',
      fieldCode: 'F-004',
      location: '温室中央控制室',
      installDate: '2024-08-05',
      ipAddress: '192.168.1.104',
      port: 8080,
      protocol: 'HTTP',
      lastOnlineTime: '2024-10-23 14:32:00',
      workingHours: 856,
      contact: '赵六',
      contactPhone: '13800138004',
      notes: '新设备，配备AI智能控制系统',
    },
    {
      id: 'wfd-5',
      deviceNo: 'WF-2024-005',
      deviceName: '5号果园滴灌水肥机',
      model: 'SF-1500',
      manufacturer: '农智通',
      status: '正常',
      fieldName: '5号苹果园',
      fieldCode: 'F-005',
      location: '果园灌溉泵房',
      installDate: '2024-04-20',
      ipAddress: '192.168.1.105',
      port: 502,
      protocol: 'Modbus-TCP',
      lastOnlineTime: '2024-10-23 14:25:00',
      workingHours: 2150,
      contact: '孙七',
      contactPhone: '13800138005',
      notes: '运行稳定，定期维护',
    },
  ]);

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingDevice, setEditingDevice] = useState<WFDevice | null>(null);
  const [viewingDevice, setViewingDevice] = useState<WFDevice | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<WFDevice | null>(null);

  // 搜索和筛选状态
  const [searchText, setSearchText] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterField, setFilterField] = useState<string>('all');

  // 表单状态
  const [formData, setFormData] = useState<Partial<WFDevice>>({});

  // 过滤设备列表
  const filteredDevices = devices.filter(device => {
    const matchSearch = searchText === '' || 
      device.deviceName.toLowerCase().includes(searchText.toLowerCase()) ||
      device.deviceNo.toLowerCase().includes(searchText.toLowerCase()) ||
      device.model.toLowerCase().includes(searchText.toLowerCase());
    
    const matchStatus = filterStatus === 'all' || device.status === filterStatus;
    const matchField = filterField === 'all' || device.fieldCode === filterField;
    
    return matchSearch && matchStatus && matchField;
  });

  // 状态统计
  const statusStats = {
    total: devices.length,
    normal: devices.filter(d => d.status === '正常').length,
    disabled: devices.filter(d => d.status === '停用').length,
  };

  const getStatusColor = (status: DeviceStatus) => {
    switch (status) {
      case '正常': return 'bg-green-100 text-green-700 border-green-200';
      case '停用': return 'bg-gray-100 text-gray-700 border-gray-200';
      default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const getStatusIcon = (status: DeviceStatus) => {
    switch (status) {
      case '正常': return <CheckCircle className="w-4 h-4" />;
      case '停用': return <XCircle className="w-4 h-4" />;
      default: return <Info className="w-4 h-4" />;
    }
  };

  // 新增设备
  const handleAdd = () => {
    setEditingDevice(null);
    setFormData({
      deviceNo: `WF-${new Date().getFullYear()}-${String(devices.length + 1).padStart(3, '0')}`,
      status: '正常',
      protocol: 'Modbus-TCP',
      port: 502,
      workingHours: 0,
    });
    setShowDialog(true);
  };

  // 编辑设备
  const handleEdit = (device: WFDevice) => {
    setEditingDevice(device);
    setFormData(device);
    setShowDialog(true);
  };

  // 查看详情
  const handleView = (device: WFDevice) => {
    setViewingDevice(device);
    setShowDetailDialog(true);
  };

  // 删除设备
  const handleDelete = (device: WFDevice) => {
    setDeleteTarget(device);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      setDevices(devices.filter(d => d.id !== deleteTarget.id));
      toast.success(`设备 ${deleteTarget.deviceName} 已删除`);
      setShowDeleteDialog(false);
      setDeleteTarget(null);
    }
  };

  // 保存设备
  const handleSave = () => {
    if (!formData.deviceName || !formData.model || !formData.fieldName) {
      toast.error('请填写必填项');
      return;
    }

    if (editingDevice) {
      // 更新
      setDevices(devices.map(d => 
        d.id === editingDevice.id ? { ...d, ...formData } as WFDevice : d
      ));
      toast.success('设备信息已更新');
    } else {
      // 新增
      const newDevice: WFDevice = {
        ...formData,
        id: `wfd-${Date.now()}`,
        lastOnlineTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      } as WFDevice;
      setDevices([...devices, newDevice]);
      toast.success('设备添加成功');
    }
    setShowDialog(false);
    setFormData({});
  };



  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">水肥机设备管理</h2>
          <p className="text-sm text-muted-foreground mt-1">
            实现对农场中所有水肥机设备的数字化映射与集中管理
          </p>
        </div>

      </div>

      {/* 功能说明卡片 */}
      <Card className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
        <div className="flex items-start gap-2">
          <Server className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-green-900">
            <p className="mb-2">水肥机设备管理核心功能：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>数字化映射</strong>：实现农场所有水肥机设备的数字化管理</li>
              <li>• <strong>设备档案</strong>：记录型号、状态、所属地块、安装位置等完整信息</li>
              <li>• <strong>状态监控</strong>：实时显示设备在线/离线状态、工作时长、最后在线时间</li>
              <li>• <strong>网络配置</strong>：支持IP地址、端口、通信协议等网络参数配置</li>
              <li>• <strong>完整CRUD</strong>：新增注册、信息修改、详情查看、条件搜索、设备删除</li>
              <li>• <strong>数据一致</strong>：确保系统信息与实际部署保持一致</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">设备总数</p>
              <p className="mt-2 text-3xl text-blue-600">{statusStats.total}</p>
            </div>
            <Server className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">正常运行</p>
              <p className="mt-2 text-3xl text-green-600">{statusStats.normal}</p>
            </div>
            <CheckCircle className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">停用设备</p>
              <p className="mt-2 text-3xl text-gray-600">{statusStats.disabled}</p>
            </div>
            <XCircle className="w-12 h-12 text-gray-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex gap-4 flex-1">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索设备名称、编号、型号..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="设备状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="正常">正常</SelectItem>
                <SelectItem value="停用">停用</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterField} onValueChange={setFilterField}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="所属地块" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部地块</SelectItem>
                {fieldsList.map((field) => (
                  <SelectItem key={field.id} value={field.code}>
                    {field.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <Button className="bg-green-600 hover:bg-green-700" onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增设备
          </Button>
        </div>
      </Card>

      {/* 设备列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>设备信息</TableHead>
              <TableHead>型号/厂商</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>所属地块</TableHead>
              <TableHead>网络配置</TableHead>
              <TableHead>工作状态</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredDevices.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  <Server className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>暂无设备数据</p>
                </TableCell>
              </TableRow>
            ) : (
              filteredDevices.map((device) => (
                <TableRow key={device.id}>
                  <TableCell>
                    <div>
                      <div className="font-medium">{device.deviceName}</div>
                      <div className="text-xs text-muted-foreground">#{device.deviceNo}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{device.model}</div>
                      <div className="text-xs text-muted-foreground">{device.manufacturer}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={getStatusColor(device.status)}>
                      <span className="flex items-center gap-1">
                        {getStatusIcon(device.status)}
                        {device.status}
                      </span>
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div className="font-medium">{device.fieldName}</div>
                      <div className="text-xs text-muted-foreground flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {device.location}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs space-y-1">
                      <div className="flex items-center gap-1">
                        <Wifi className="w-3 h-3 text-muted-foreground" />
                        <span className="font-mono">{device.ipAddress}:{device.port}</span>
                      </div>
                      <div>
                        <Badge variant="outline" className="text-xs">{device.protocol}</Badge>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs space-y-1">
                      <div className="flex items-center gap-1">
                        <Clock className="w-3 h-3 text-muted-foreground" />
                        运行: {device.workingHours}小时
                      </div>
                      <div className="text-muted-foreground">
                        {device.lastOnlineTime.substring(5, 16)}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2 justify-end">
                      <Button size="sm" variant="outline" onClick={() => handleView(device)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEdit(device)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDelete(device)}
                        className="text-red-600 hover:text-red-700 hover:border-red-300"
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 新增/编辑设备对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingDevice ? '编辑设备信息' : '新增水肥机设备'}
            </DialogTitle>
            <DialogDescription>
              {editingDevice ? '修改设备信息，确保数据准确' : '录入新设备信息，确保与实际部署一致'}
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4">
            {/* 基本信息 */}
            <div className="col-span-2">
              <h4 className="mb-3 text-green-700">基本信息</h4>
            </div>

            <div>
              <Label>设备编号 *</Label>
              <Input
                value={formData.deviceNo || ''}
                onChange={(e) => setFormData({ ...formData, deviceNo: e.target.value })}
                placeholder="WF-2024-001"
                disabled={!!editingDevice}
              />
            </div>

            <div>
              <Label>设备名称 *</Label>
              <Input
                value={formData.deviceName || ''}
                onChange={(e) => setFormData({ ...formData, deviceName: e.target.value })}
                placeholder="1号大棚水肥一体机"
              />
            </div>

            <div>
              <Label>设备型号 *</Label>
              <Input
                value={formData.model || ''}
                onChange={(e) => setFormData({ ...formData, model: e.target.value })}
                placeholder="SF-3000Pro"
              />
            </div>

            <div>
              <Label>生产厂商</Label>
              <Input
                value={formData.manufacturer || ''}
                onChange={(e) => setFormData({ ...formData, manufacturer: e.target.value })}
                placeholder="智农科技"
              />
            </div>

            <div>
              <Label>设备状态 *</Label>
              <Select
                value={formData.status || '正常'}
                onValueChange={(value: DeviceStatus) => setFormData({ ...formData, status: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="正常">正常</SelectItem>
                  <SelectItem value="停用">停用</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>安装日期</Label>
              <Input
                type="date"
                value={formData.installDate || ''}
                onChange={(e) => setFormData({ ...formData, installDate: e.target.value })}
              />
            </div>

            {/* 地块信息 */}
            <div className="col-span-2 mt-4">
              <h4 className="mb-3 text-green-700">地块信息</h4>
            </div>

            <div className="col-span-2">
              <Label>所属地块 *</Label>
              <Select
                value={formData.fieldCode || ''}
                onValueChange={(value) => {
                  const selectedField = fieldsList.find(f => f.code === value);
                  if (selectedField) {
                    setFormData({ 
                      ...formData, 
                      fieldCode: selectedField.code,
                      fieldName: selectedField.name 
                    });
                  }
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="请选择地块" />
                </SelectTrigger>
                <SelectContent>
                  {fieldsList.map((field) => (
                    <SelectItem key={field.id} value={field.code}>
                      {field.name} ({field.code}) - {field.area}亩
                      {field.cropType && ` - ${field.cropType}`}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {formData.fieldName && (
                <p className="text-xs text-muted-foreground mt-1">
                  已选择：{formData.fieldName} ({formData.fieldCode})
                </p>
              )}
            </div>

            <div className="col-span-2">
              <Label>安装位置</Label>
              <Input
                value={formData.location || ''}
                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                placeholder="大棚东南角控制柜"
              />
            </div>

            {/* 网络配置 */}
            <div className="col-span-2 mt-4">
              <h4 className="mb-3 text-green-700">网络配置</h4>
            </div>

            <div>
              <Label>IP地址</Label>
              <Input
                value={formData.ipAddress || ''}
                onChange={(e) => setFormData({ ...formData, ipAddress: e.target.value })}
                placeholder="192.168.1.101"
              />
            </div>

            <div>
              <Label>端口号</Label>
              <Input
                type="number"
                value={formData.port || ''}
                onChange={(e) => setFormData({ ...formData, port: Number(e.target.value) })}
                placeholder="502"
              />
            </div>

            <div className="col-span-2">
              <Label>通信协议</Label>
              <Select
                value={formData.protocol || 'Modbus-TCP'}
                onValueChange={(value: ProtocolType) => setFormData({ ...formData, protocol: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Modbus-RTU">Modbus-RTU</SelectItem>
                  <SelectItem value="Modbus-TCP">Modbus-TCP</SelectItem>
                  <SelectItem value="HTTP">HTTP</SelectItem>
                  <SelectItem value="MQTT">MQTT</SelectItem>
                  <SelectItem value="OPC-UA">OPC-UA</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 联系信息 */}
            <div className="col-span-2 mt-4">
              <h4 className="mb-3 text-green-700">联系信息</h4>
            </div>

            <div>
              <Label>负责人</Label>
              <Input
                value={formData.contact || ''}
                onChange={(e) => setFormData({ ...formData, contact: e.target.value })}
                placeholder="张三"
              />
            </div>

            <div>
              <Label>联系电话</Label>
              <Input
                value={formData.contactPhone || ''}
                onChange={(e) => setFormData({ ...formData, contactPhone: e.target.value })}
                placeholder="13800138001"
              />
            </div>

            <div className="col-span-2">
              <Label>备注说明</Label>
              <Textarea
                value={formData.notes || ''}
                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                placeholder="设备的其他说明信息..."
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 设备详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>设备详细信息</DialogTitle>
            <DialogDescription>
              查看设备完整信息
            </DialogDescription>
          </DialogHeader>

          {viewingDevice && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <Info className="w-4 h-4" />
                  基本信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>设备编号</Label>
                    <div className="field-value">{viewingDevice.deviceNo}</div>
                  </div>
                  <div>
                    <Label>设备名称</Label>
                    <div className="field-value">{viewingDevice.deviceName}</div>
                  </div>
                  <div>
                    <Label>设备型号</Label>
                    <div className="field-value">{viewingDevice.model}</div>
                  </div>
                  <div>
                    <Label>生产厂商</Label>
                    <div className="field-value">{viewingDevice.manufacturer}</div>
                  </div>
                  <div>
                    <Label>设备状态</Label>
                    <div className="mt-2">
                      <Badge className={getStatusColor(viewingDevice.status)}>
                        <span className="flex items-center gap-1">
                          {getStatusIcon(viewingDevice.status)}
                          {viewingDevice.status}
                        </span>
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>安装日期</Label>
                    <div className="field-value flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-muted-foreground" />
                      {viewingDevice.installDate}
                    </div>
                  </div>
                </div>
              </div>

              {/* 地块信息 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <MapPin className="w-4 h-4" />
                  地块信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>所属地块</Label>
                    <div className="field-value">{viewingDevice.fieldName}</div>
                  </div>
                  <div>
                    <Label>地块编号</Label>
                    <div className="field-value">{viewingDevice.fieldCode}</div>
                  </div>
                  <div className="col-span-2">
                    <Label>安装位置</Label>
                    <div className="field-value">{viewingDevice.location}</div>
                  </div>
                </div>
              </div>

              {/* 网络配置 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <Wifi className="w-4 h-4" />
                  网络配置
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>IP地址</Label>
                    <div className="field-value font-mono">{viewingDevice.ipAddress || '-'}</div>
                  </div>
                  <div>
                    <Label>端口号</Label>
                    <div className="field-value font-mono">{viewingDevice.port || '-'}</div>
                  </div>
                  <div className="col-span-2">
                    <Label>通信协议</Label>
                    <div className="mt-2">
                      <Badge variant="outline">{viewingDevice.protocol}</Badge>
                    </div>
                  </div>
                </div>
              </div>

              {/* 工作状态 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <Activity className="w-4 h-4" />
                  工作状态
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>累计运行时长</Label>
                    <div className="field-value">{viewingDevice.workingHours} 小时</div>
                  </div>
                  <div>
                    <Label>最后在线时间</Label>
                    <div className="field-value">{viewingDevice.lastOnlineTime}</div>
                  </div>
                </div>
              </div>

              {/* 联系信息 */}
              {(viewingDevice.contact || viewingDevice.contactPhone) && (
                <div>
                  <h4 className="mb-3 text-green-700">联系信息</h4>
                  <div className="grid grid-cols-2 gap-4">
                    {viewingDevice.contact && (
                      <div>
                        <Label>负责人</Label>
                        <div className="field-value">{viewingDevice.contact}</div>
                      </div>
                    )}
                    {viewingDevice.contactPhone && (
                      <div>
                        <Label>联系电话</Label>
                        <div className="field-value">{viewingDevice.contactPhone}</div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 备注 */}
              {viewingDevice.notes && (
                <div>
                  <Label>备注说明</Label>
                  <div className="field-value">{viewingDevice.notes}</div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700"
              onClick={() => {
                if (viewingDevice) {
                  setShowDetailDialog(false);
                  handleEdit(viewingDevice);
                }
              }}
            >
              <Edit className="w-4 h-4 mr-2" />
              编辑
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除设备</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除设备 <strong className="text-foreground">{deleteTarget?.deviceName}</strong> (#{deleteTarget?.deviceNo}) 吗？
              <br />
              <br />
              删除后将无法恢复，请谨慎操作。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction 
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
