import { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import { Card } from '../ui/card';
import { Badge } from '../ui/badge';
import { Plus, Edit, Trash2, Eye } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { toast } from 'sonner@2.0.3';
import { useForm } from 'react-hook-form@7.55.0';

// 参数定义接口
interface ParameterDefinition {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select';
  required?: boolean;
  defaultValue?: any;
  options?: { label: string; value: any }[];
  unit?: string;
  min?: number;
  max?: number;
  description?: string;
}

// 设备类型接口
interface DeviceType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[];
  createdAt: string;
  updatedAt: string;
}

export function DeviceType() {
  const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
  const [showDialog, setShowDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [showParamsDialog, setShowParamsDialog] = useState(false);
  const [editingType, setEditingType] = useState<DeviceType | null>(null);
  const [viewingType, setViewingType] = useState<DeviceType | null>(null);
  const [viewingParams, setViewingParams] = useState<DeviceType | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);

  const { register, handleSubmit, setValue, reset, formState: { errors } } = useForm();

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

  const loadData = () => {
    const data = localStorage.getItem('smart_agriculture_ai_device_types');
    if (data) {
      const types = JSON.parse(data);
      const normalizedTypes = types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      }));
      setDeviceTypes(normalizedTypes);
    } else {
      const mockTypes: DeviceType[] = [
        {
          id: 'device-type-1',
          name: '土壤传感器',
          manufacturer: '施耐德',
          model: 'SOIL-100',
          description: '高精度土壤温湿度、养分监测传感器',
          parameterDefinitions: [
            {
              key: 'measurementInterval',
              label: '测量间隔',
              type: 'number',
              unit: '分钟',
              required: true,
              defaultValue: 30,
              min: 5,
              max: 120,
              description: '数据测量时间间隔'
            },
            {
              key: 'uploadMode',
              label: '上传模式',
              type: 'select',
              options: [
                { label: '实时上传', value: 'realtime' },
                { label: '定时上传', value: 'scheduled' }
              ],
              defaultValue: 'scheduled',
              description: '数据上传方式'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-2',
          name: '气象站',
          manufacturer: '华为',
          model: 'WEATHER-200',
          description: '多参数气象监测站，支持温度、湿度、风速、降雨量等监测',
          parameterDefinitions: [
            {
              key: 'sampleRate',
              label: '采样频率',
              type: 'number',
              unit: '次/小时',
              required: true,
              defaultValue: 12,
              min: 1,
              max: 60,
              description: '每小时采集次数'
            },
            {
              key: 'windSpeedUnit',
              label: '风速单位',
              type: 'select',
              options: [
                { label: '米/秒', value: 'm/s' },
                { label: '公里/小时', value: 'km/h' }
              ],
              defaultValue: 'm/s'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-3',
          name: '虫情监测仪',
          manufacturer: '托普云农',
          model: 'PEST-300',
          description: 'AI智能虫情监测仪，自动拍照识别害虫种类和数量',
          parameterDefinitions: [
            {
              key: 'photoInterval',
              label: '拍照间隔',
              type: 'number',
              unit: '小时',
              required: true,
              defaultValue: 2,
              min: 1,
              max: 24,
              description: '自动拍照时间间隔'
            },
            {
              key: 'aiRecognition',
              label: 'AI识别',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用AI自动识别'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-4',
          name: '水质监测仪',
          manufacturer: '海康威视',
          model: 'WATER-400',
          description: '多参数水质在线监测仪，支持pH、溶解氧、浊度等监测',
          parameterDefinitions: [
            {
              key: 'measurementCycle',
              label: '测量周期',
              type: 'number',
              unit: '分钟',
              required: true,
              defaultValue: 15,
              min: 5,
              max: 60
            },
            {
              key: 'alarmEnabled',
              label: '启用预警',
              type: 'boolean',
              defaultValue: true
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-5',
          name: '灌溉控制器',
          manufacturer: '大疆',
          model: 'IRRI-500',
          description: '智能灌溉控制器，支持远程控制和定时灌溉',
          parameterDefinitions: [
            {
              key: 'controlMode',
              label: '控制模式',
              type: 'select',
              options: [
                { label: '手动控制', value: 'manual' },
                { label: '自动控制', value: 'auto' },
                { label: '定时控制', value: 'scheduled' }
              ],
              required: true,
              defaultValue: 'auto'
            },
            {
              key: 'flowRateLimit',
              label: '流量限制',
              type: 'number',
              unit: 'L/min',
              defaultValue: 100,
              min: 10,
              max: 500
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-6',
          name: 'GPS定位终端',
          manufacturer: '中国北斗',
          model: 'BD-GPS-1000',
          description: '北斗/GPS双模定位终端，实时位置追踪和轨迹记录',
          parameterDefinitions: [
            {
              key: 'positionInterval',
              label: '定位间隔',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 300,
              description: '位置更新时间间隔'
            },
            {
              key: 'workMode',
              label: '工作模式',
              type: 'select',
              options: [
                { label: '北斗优先', value: 'beidou' },
                { label: 'GPS优先', value: 'gps' },
                { label: '双模', value: 'dual' }
              ],
              defaultValue: 'dual',
              description: '定位系统选择'
            },
            {
              key: 'savePath',
              label: '保存轨迹',
              type: 'boolean',
              defaultValue: true,
              description: '是否保存历史轨迹'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-7',
          name: '高清摄像头',
          manufacturer: '海康威视',
          model: 'HIK-CAM-2000',
          description: '4K高清摄像头，支持夜视、变焦和AI识别',
          parameterDefinitions: [
            {
              key: 'resolution',
              label: '分辨率',
              type: 'select',
              options: [
                { label: '1080P', value: '1080' },
                { label: '2K', value: '2k' },
                { label: '4K', value: '4k' }
              ],
              required: true,
              defaultValue: '4k'
            },
            {
              key: 'frameRate',
              label: '帧率',
              type: 'number',
              unit: 'fps',
              defaultValue: 30,
              min: 15,
              max: 60,
              description: '视频帧率'
            },
            {
              key: 'nightVision',
              label: '夜视功能',
              type: 'boolean',
              defaultValue: true
            },
            {
              key: 'recordMode',
              label: '录像模式',
              type: 'select',
              options: [
                { label: '连续录像', value: 'continuous' },
                { label: '事件触发', value: 'event' },
                { label: '定时录像', value: 'scheduled' }
              ],
              defaultValue: 'event'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-8',
          name: '油耗监测仪',
          manufacturer: '博世',
          model: 'BOSCH-FUEL-300',
          description: '精密油耗监测仪，实时监测燃油消耗和液位',
          parameterDefinitions: [
            {
              key: 'updateInterval',
              label: '更新间隔',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 5,
              min: 1,
              max: 60,
              description: '数据更新频率'
            },
            {
              key: 'alarmThreshold',
              label: '低油位报警',
              type: 'number',
              unit: '%',
              defaultValue: 20,
              min: 5,
              max: 50,
              description: '低于此百分比时报警'
            },
            {
              key: 'dataStorage',
              label: '数据存储',
              type: 'boolean',
              defaultValue: true,
              description: '是否存储历史数据'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-9',
          name: '转速传感器',
          manufacturer: '西门子',
          model: 'SIEMENS-RPM-500',
          description: '高精度转速传感器，用于监测发动机和作业部件转速',
          parameterDefinitions: [
            {
              key: 'samplingRate',
              label: '采样率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 100,
              min: 10,
              max: 1000,
              description: '每秒采样次数'
            },
            {
              key: 'maxRPM',
              label: '最大转速',
              type: 'number',
              unit: 'RPM',
              required: true,
              defaultValue: 3000,
              min: 500,
              max: 10000
            },
            {
              key: 'overSpeedAlarm',
              label: '超速报警',
              type: 'boolean',
              defaultValue: true
            },
            {
              key: 'alarmRPM',
              label: '报警转速',
              type: 'number',
              unit: 'RPM',
              defaultValue: 2800,
              min: 100,
              max: 10000
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-10',
          name: '作业深度传感器',
          manufacturer: '约翰迪尔',
          model: 'JD-DEPTH-600',
          description: '耕作深度监测传感器，确保作业深度一致性',
          parameterDefinitions: [
            {
              key: 'measurementUnit',
              label: '测量单位',
              type: 'select',
              options: [
                { label: '厘米', value: 'cm' },
                { label: '英寸', value: 'inch' }
              ],
              required: true,
              defaultValue: 'cm'
            },
            {
              key: 'targetDepth',
              label: '目标深度',
              type: 'number',
              unit: 'cm',
              required: true,
              defaultValue: 25,
              min: 5,
              max: 50,
              description: '期望耕作深度'
            },
            {
              key: 'tolerance',
              label: '容差范围',
              type: 'number',
              unit: 'cm',
              defaultValue: 3,
              min: 1,
              max: 10,
              description: '允许偏差范围'
            },
            {
              key: 'autoAdjust',
              label: '自动调整',
              type: 'boolean',
              defaultValue: false,
              description: '是否自动调整深度'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-11',
          name: '作业宽度传感器',
          manufacturer: '凯斯纽荷兰',
          model: 'CNH-WIDTH-700',
          description: '作业幅宽监测传感器，精确计算作业面积',
          parameterDefinitions: [
            {
              key: 'width',
              label: '作业幅宽',
              type: 'number',
              unit: '米',
              required: true,
              defaultValue: 3.0,
              min: 0.5,
              max: 12.0,
              description: '实际作业宽度'
            },
            {
              key: 'overlapDetection',
              label: '重叠检测',
              type: 'boolean',
              defaultValue: true,
              description: '是否检测重叠作业'
            },
            {
              key: 'areaCalculation',
              label: '面积计算',
              type: 'select',
              options: [
                { label: '实时计算', value: 'realtime' },
                { label: '事后计算', value: 'offline' }
              ],
              defaultValue: 'realtime'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-12',
          name: '温度传感器',
          manufacturer: '欧姆龙',
          model: 'OMRON-TEMP-800',
          description: '多点温度监测传感器，用于发动机和液压系统监测',
          parameterDefinitions: [
            {
              key: 'measurementPoints',
              label: '测量点数',
              type: 'number',
              required: true,
              defaultValue: 4,
              min: 1,
              max: 8,
              description: '同时监测的位置数量'
            },
            {
              key: 'updateFrequency',
              label: '更新频率',
              type: 'number',
              unit: '秒',
              defaultValue: 3,
              min: 1,
              max: 30
            },
            {
              key: 'highTempAlarm',
              label: '高温报警',
              type: 'number',
              unit: '℃',
              defaultValue: 90,
              min: 50,
              max: 150,
              description: '高温报警阈值'
            },
            {
              key: 'lowTempAlarm',
              label: '低温报警',
              type: 'number',
              unit: '℃',
              defaultValue: -10,
              min: -40,
              max: 20,
              description: '低温报警阈值'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-13',
          name: '振动传感器',
          manufacturer: 'ABB',
          model: 'ABB-VIB-900',
          description: '三轴振动传感器，监测设备运行状态和异常振动',
          parameterDefinitions: [
            {
              key: 'sensitivity',
              label: '灵敏度',
              type: 'select',
              options: [
                { label: '低', value: 'low' },
                { label: '中', value: 'medium' },
                { label: '高', value: 'high' }
              ],
              required: true,
              defaultValue: 'medium'
            },
            {
              key: 'samplingRate',
              label: '采样频率',
              type: 'number',
              unit: 'Hz',
              defaultValue: 200,
              min: 50,
              max: 1000
            },
            {
              key: 'alarmLevel',
              label: '报警等级',
              type: 'number',
              unit: 'g',
              defaultValue: 5.0,
              min: 1.0,
              max: 20.0,
              description: '超过此加速度值时报警'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-14',
          name: '产量监测仪',
          manufacturer: '爱科',
          model: 'AGCO-YIELD-1000',
          description: '实时产量监测仪，精确记录收获产量和分布',
          parameterDefinitions: [
            {
              key: 'calibrationFactor',
              label: '校准系数',
              type: 'number',
              required: true,
              defaultValue: 1.0,
              min: 0.5,
              max: 2.0,
              description: '产量计算校准参数'
            },
            {
              key: 'moistureCorrection',
              label: '水分校正',
              type: 'boolean',
              defaultValue: true,
              description: '是否进行水分含量校正'
            },
            {
              key: 'dataResolution',
              label: '数据分辨率',
              type: 'select',
              options: [
                { label: '1米', value: '1m' },
                { label: '5米', value: '5m' },
                { label: '10米', value: '10m' }
              ],
              defaultValue: '5m',
              description: '产量地图分辨率'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-15',
          name: '自动驾驶控制器',
          manufacturer: '天宝',
          model: 'TRIMBLE-AUTO-2000',
          description: 'RTK自动驾驶控制系统，厘米级精度导航',
          parameterDefinitions: [
            {
              key: 'accuracyMode',
              label: '精度模式',
              type: 'select',
              options: [
                { label: '标准(±30cm)', value: 'standard' },
                { label: '高精度(±10cm)', value: 'high' },
                { label: 'RTK(±2cm)', value: 'rtk' }
              ],
              required: true,
              defaultValue: 'rtk'
            },
            {
              key: 'steeringSpeed',
              label: '转向速度',
              type: 'number',
              unit: '度/秒',
              defaultValue: 30,
              min: 10,
              max: 60,
              description: '最大转向角速度'
            },
            {
              key: 'autoTurnEnabled',
              label: '自动转弯',
              type: 'boolean',
              defaultValue: true
            },
            {
              key: 'pathPlanning',
              label: '路径规划',
              type: 'select',
              options: [
                { label: '直线', value: 'straight' },
                { label: '曲线', value: 'curve' },
                { label: 'AB线', value: 'ab_line' },
                { label: '环绕', value: 'contour' }
              ],
              defaultValue: 'ab_line'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(mockTypes));
      // 同步到农机负载管理使用的数据源
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(mockTypes));
      setDeviceTypes(mockTypes);
    }
  };

  const onSubmit = (data: any) => {
    if (editingType) {
      const updated: DeviceType = {
        ...editingType,
        ...data,
        updatedAt: new Date().toISOString(),
      };
      const newTypes = deviceTypes.map(t => t.id === updated.id ? updated : t);
      setDeviceTypes(newTypes);
      localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(newTypes));
      // 同步到农机负载管理使用的数据源
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(newTypes));
      toast.success('设备类型更新成功');
    } else {
      const newType: DeviceType = {
        id: `device-type-${Date.now()}`,
        ...data,
        parameterDefinitions: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const newTypes = [...deviceTypes, newType];
      setDeviceTypes(newTypes);
      localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(newTypes));
      // 同步到农机负载管理使用的数据源
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(newTypes));
      toast.success('设备类型添加成功');
    }

    setShowDialog(false);
    setEditingType(null);
    reset();
  };

  const handleEdit = (type: DeviceType) => {
    setEditingType(type);
    setValue('name', type.name);
    setValue('manufacturer', type.manufacturer || '');
    setValue('model', type.model || '');
    setValue('description', type.description || '');
    setShowDialog(true);
  };

  const handleView = (type: DeviceType) => {
    setViewingType(type);
    setShowViewDialog(true);
  };

  const handleViewParams = (type: DeviceType) => {
    setViewingParams(type);
    setShowParamsDialog(true);
  };

  const handleDeleteClick = (id: string) => {
    setPendingDeleteId(id);
    setShowDeleteConfirm(true);
  };

  const confirmDelete = () => {
    if (pendingDeleteId) {
      const newTypes = deviceTypes.filter(t => t.id !== pendingDeleteId);
      setDeviceTypes(newTypes);
      localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(newTypes));
      // 同步到农机负载管理使用的数据源
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(newTypes));
      toast.success('设备类型删除成功');
    }
    setShowDeleteConfirm(false);
    setPendingDeleteId(null);
  };

  const getParamTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      'number': '数字',
      'string': '文本',
      'boolean': '布尔',
      'select': '选择'
    };
    return labels[type] || type;
  };

  const totalParams = deviceTypes.reduce((sum, type) => sum + (type.parameterDefinitions?.length || 0), 0);
  const typesWithParams = deviceTypes.filter(type => (type.parameterDefinitions?.length || 0) > 0).length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">设备类型管理</h2>
          <p className="text-muted-foreground">定义和管理物联设备的类型信息</p>
        </div>
        <Button onClick={() => {
          setEditingType(null);
          reset();
          setShowDialog(true);
        }}>
          <Plus className="w-4 h-4 mr-2" />
          新增类型
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总类型数</div>
          <div className="mt-1">{deviceTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">参数模板总数</div>
          <div className="mt-1 text-primary">{totalParams}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已配置模板</div>
          <div className="mt-1">{typesWithParams} / {deviceTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写品牌</div>
          <div className="mt-1 text-info">
            {deviceTypes.filter(t => t.manufacturer).length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写型号</div>
          <div className="mt-1">
            {deviceTypes.filter(t => t.model).length}
          </div>
        </Card>
      </div>

      {/* 类型列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>类型名称</TableHead>
              <TableHead>品牌</TableHead>
              <TableHead>型号</TableHead>
              <TableHead>描述</TableHead>
              <TableHead>参数模板</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {deviceTypes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              deviceTypes.map(type => (
                <TableRow key={type.id}>
                  <TableCell>{type.name}</TableCell>
                  <TableCell>{type.manufacturer || '-'}</TableCell>
                  <TableCell>{type.model || '-'}</TableCell>
                  <TableCell className="max-w-md">
                    <div className="truncate">
                      {type.description || '-'}
                    </div>
                  </TableCell>
                  <TableCell>
                    {(type.parameterDefinitions?.length || 0) > 0 ? (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewParams(type)}
                        className="text-primary hover:text-primary/80"
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        {type.parameterDefinitions.length} 个参数
                      </Button>
                    ) : (
                      <span className="text-muted-foreground text-sm">未定义</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => handleView(type)}
                        title="查看"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => handleEdit(type)}
                        title="编辑"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick(type.id)}
                        title="删除"
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 添加/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingType ? '编辑设备类型' : '新增设备类型'}</DialogTitle>
            <DialogDescription>
              填写设备类型的基本信息
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">类型名称 *</Label>
                <Input
                  id="name"
                  {...register('name', { required: '请输入类型名称' })}
                  placeholder="例如：土壤传感器"
                />
                {errors.name && (
                  <p className="text-sm text-destructive">{errors.name.message as string}</p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="manufacturer">品牌</Label>
                <Input
                  id="manufacturer"
                  {...register('manufacturer')}
                  placeholder="例如：施耐德"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="model">型号</Label>
                <Input
                  id="model"
                  {...register('model')}
                  placeholder="例如：SOIL-100"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">描述</Label>
              <Textarea
                id="description"
                {...register('description')}
                placeholder="设备类型的详细描述..."
                rows={3}
              />
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setShowDialog(false)}>
                取消
              </Button>
              <Button type="submit">
                {editingType ? '保存' : '添加'}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>设备类型详情</DialogTitle>
          </DialogHeader>
          {viewingType && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-muted-foreground">类型名称</label>
                  <div className="field-value">{viewingType.name}</div>
                </div>
                <div>
                  <label className="text-muted-foreground">品牌</label>
                  <div className="field-value">{viewingType.manufacturer || '-'}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-muted-foreground">型号</label>
                  <div className="field-value">{viewingType.model || '-'}</div>
                </div>
                <div>
                  <label className="text-muted-foreground">参数模板数</label>
                  <div className="field-value">
                    {viewingType.parameterDefinitions?.length || 0} 个
                  </div>
                </div>
              </div>
              <div>
                <label className="text-muted-foreground">描述</label>
                <div className="field-value">{viewingType.description || '-'}</div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-muted-foreground">创建时间</label>
                  <div className="field-value">
                    {new Date(viewingType.createdAt).toLocaleString('zh-CN')}
                  </div>
                </div>
                <div>
                  <label className="text-muted-foreground">更新时间</label>
                  <div className="field-value">
                    {new Date(viewingType.updatedAt).toLocaleString('zh-CN')}
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button onClick={() => setShowViewDialog(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看参数模板对话框 */}
      <Dialog open={showParamsDialog} onOpenChange={setShowParamsDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>参数模板 - {viewingParams?.name}</DialogTitle>
            <DialogDescription>
              该设备类型的参数定义
            </DialogDescription>
          </DialogHeader>
          {viewingParams && viewingParams.parameterDefinitions.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>参数标识</TableHead>
                  <TableHead>参数名称</TableHead>
                  <TableHead>数据类型</TableHead>
                  <TableHead>必填</TableHead>
                  <TableHead>默认值</TableHead>
                  <TableHead>单位</TableHead>
                  <TableHead>范围</TableHead>
                  <TableHead>说明</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {viewingParams.parameterDefinitions.map((param, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-mono text-sm">{param.key}</TableCell>
                    <TableCell>{param.label}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{getParamTypeLabel(param.type)}</Badge>
                    </TableCell>
                    <TableCell>
                      {param.required ? (
                        <Badge className="bg-error-muted text-error-muted-foreground">是</Badge>
                      ) : (
                        <span className="text-muted-foreground">否</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {param.type === 'boolean' 
                        ? (param.defaultValue ? '是' : '否')
                        : (param.defaultValue?.toString() || '-')
                      }
                    </TableCell>
                    <TableCell>{param.unit || '-'}</TableCell>
                    <TableCell>
                      {param.min !== undefined && param.max !== undefined
                        ? `${param.min} ~ ${param.max}`
                        : '-'
                      }
                    </TableCell>
                    <TableCell className="max-w-xs">
                      <div className="truncate" title={param.description}>
                        {param.description || '-'}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="text-center text-muted-foreground py-8">
              该设备类型暂无参数定义
            </div>
          )}
          <DialogFooter>
            <Button onClick={() => setShowParamsDialog(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除此设备类型吗？此操作不可撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
