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,
  Cpu,
  CheckCircle,
  AlertCircle,
  Link2,
  Calendar,
  Package,
  Wifi,
  WifiOff,
  AlertTriangle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

type ComponentType = '泵体' | '传感器' | '控制器' | '阀门' | '流量计' | '搅拌器' | '加热器';
type ComponentStatus = '在线' | '异常' | '离线';

interface WFParameter {
  id: string;
  parameterNo: string;
  parameterName: string;
  type: string;
  unit: string;
  minValue: number;
  maxValue: number;
  description: string;
}

interface WFComponent {
  id: string;
  componentNo: string;
  componentName: string;
  type: ComponentType;
  deviceName: string;
  deviceNo: string;
  specification: string;
  manufacturer: string;
  model: string;
  serialNumber?: string;
  installDate: string;
  status: ComponentStatus;
  // 关联的参数
  linkedParameters: string[]; // 参数ID数组
  // 其他信息
  warrantyPeriod?: string;
  maintenanceCycle?: number; // 维护周期（天）
  lastMaintenanceDate?: string;
  contact?: string;
  contactPhone?: string;
  notes?: string;
}

export function WaterFertilizerComponent() {
  // 预置的参数库（实际应该从参数配置中读取）
  const availableParameters: WFParameter[] = [
    {
      id: 'param-1',
      parameterNo: 'PARAM-001',
      parameterName: '系统压力',
      type: '压力',
      unit: 'bar',
      minValue: 0,
      maxValue: 10,
      description: '系统主管道压力监测',
    },
    {
      id: 'param-2',
      parameterNo: 'PARAM-002',
      parameterName: '灌溉流量',
      type: '流量',
      unit: 'L/min',
      minValue: 0,
      maxValue: 50,
      description: '主管道流量监测',
    },
    {
      id: 'param-3',
      parameterNo: 'PARAM-003',
      parameterName: '溶液EC值',
      type: 'EC值',
      unit: 'mS/cm',
      minValue: 0,
      maxValue: 5,
      description: '营养液电导率监测',
    },
    {
      id: 'param-4',
      parameterNo: 'PARAM-004',
      parameterName: '溶液PH值',
      type: 'PH值',
      unit: 'pH',
      minValue: 0,
      maxValue: 14,
      description: '营养液酸碱度监测',
    },
    {
      id: 'param-5',
      parameterNo: 'PARAM-005',
      parameterName: '水温',
      type: '温度',
      unit: '℃',
      minValue: 0,
      maxValue: 50,
      description: '灌溉水温度监测',
    },
    {
      id: 'param-6',
      parameterNo: 'PARAM-006',
      parameterName: '泵体转速',
      type: '转速',
      unit: 'RPM',
      minValue: 0,
      maxValue: 3000,
      description: '水泵转速监测',
    },
    {
      id: 'param-7',
      parameterNo: 'PARAM-007',
      parameterName: '电机功率',
      type: '功率',
      unit: 'kW',
      minValue: 0,
      maxValue: 10,
      description: '电机运行功率监测',
    },
  ];

  const [components, setComponents] = useState<WFComponent[]>([
    {
      id: 'comp-1',
      componentNo: 'COMP-2024-001',
      componentName: '1号主水泵',
      type: '泵体',
      deviceName: '1号大棚水肥一体机',
      deviceNo: 'WF-2024-001',
      specification: '1.5kW/220V',
      manufacturer: '格兰富',
      model: 'CR-15',
      serialNumber: 'GF20240315001',
      installDate: '2024-03-15',
      status: '在线',
      linkedParameters: ['param-1', 'param-2', 'param-6', 'param-7'],
      warrantyPeriod: '2年',
      maintenanceCycle: 90,
      lastMaintenanceDate: '2024-09-15',
      contact: '张三',
      contactPhone: '13800138001',
      notes: '核心部件，每季度必须保养',
    },
    {
      id: 'comp-2',
      componentNo: 'COMP-2024-002',
      componentName: '1号EC传感器',
      type: '传感器',
      deviceName: '1号大棚水肥一体机',
      deviceNo: 'WF-2024-001',
      specification: 'EC-200',
      manufacturer: '梅特勒-托利多',
      model: 'EC-200Pro',
      serialNumber: 'MT20240315002',
      installDate: '2024-03-15',
      status: '在线',
      linkedParameters: ['param-3'],
      warrantyPeriod: '1年',
      maintenanceCycle: 30,
      lastMaintenanceDate: '2024-10-01',
      contact: '张三',
      contactPhone: '13800138001',
      notes: '每月需要标定校准',
    },
    {
      id: 'comp-3',
      componentNo: 'COMP-2024-003',
      componentName: '1号PH传感器',
      type: '传感器',
      deviceName: '1号大棚水肥一体机',
      deviceNo: 'WF-2024-001',
      specification: 'PH-300',
      manufacturer: '梅特勒-托利多',
      model: 'PH-300Pro',
      serialNumber: 'MT20240315003',
      installDate: '2024-03-15',
      status: '异常',
      linkedParameters: ['param-4'],
      warrantyPeriod: '1年',
      maintenanceCycle: 30,
      lastMaintenanceDate: '2024-10-01',
      contact: '张三',
      contactPhone: '13800138001',
      notes: '每月需要标定校准',
    },
    {
      id: 'comp-4',
      componentNo: 'COMP-2024-004',
      componentName: '1号PLC控制器',
      type: '控制器',
      deviceName: '1号大棚水肥一体机',
      deviceNo: 'WF-2024-001',
      specification: 'S7-1200',
      manufacturer: '西门子',
      model: 'S7-1200',
      serialNumber: 'SM20240315004',
      installDate: '2024-03-15',
      status: '在线',
      linkedParameters: ['param-1', 'param-2', 'param-3', 'param-4'],
      warrantyPeriod: '3年',
      maintenanceCycle: 180,
      contact: '李四',
      contactPhone: '13800138002',
      notes: '核心控制单元',
    },
    {
      id: 'comp-5',
      componentNo: 'COMP-2024-005',
      componentName: '2号流量计',
      type: '流量计',
      deviceName: '2号田块智能水肥机',
      deviceNo: 'WF-2024-002',
      specification: 'FM-100',
      manufacturer: '艾默生',
      model: 'FM-100',
      serialNumber: 'EM20240520001',
      installDate: '2024-05-20',
      status: '在线',
      linkedParameters: ['param-2'],
      warrantyPeriod: '2年',
      maintenanceCycle: 60,
      lastMaintenanceDate: '2024-09-20',
      contact: '王五',
      contactPhone: '13800138003',
    },
    {
      id: 'comp-6',
      componentNo: 'COMP-2024-006',
      componentName: '3号电磁阀',
      type: '阀门',
      deviceName: '3号田块水肥一体机',
      deviceNo: 'WF-2024-003',
      specification: 'DN25 PN16',
      manufacturer: '亚德客',
      model: 'SV-25',
      installDate: '2024-06-10',
      status: '离线',
      linkedParameters: ['param-1'],
      warrantyPeriod: '1年',
      maintenanceCycle: 90,
      lastMaintenanceDate: '2024-08-10',
      notes: '开关动作异常，需要检修',
    },
  ]);

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingComponent, setEditingComponent] = useState<WFComponent | null>(null);
  const [viewingComponent, setViewingComponent] = useState<WFComponent | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<WFComponent | null>(null);

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

  // 表单数据
  const [formData, setFormData] = useState<Partial<WFComponent>>({
    linkedParameters: [],
  });

  // 过滤部件列表
  const filteredComponents = components.filter(component => {
    const matchSearch = searchText === '' || 
      component.componentName.toLowerCase().includes(searchText.toLowerCase()) ||
      component.componentNo.toLowerCase().includes(searchText.toLowerCase()) ||
      component.type.toLowerCase().includes(searchText.toLowerCase()) ||
      component.manufacturer.toLowerCase().includes(searchText.toLowerCase());
    
    const matchType = filterType === 'all' || component.type === filterType;
    const matchStatus = filterStatus === 'all' || component.status === filterStatus;
    
    return matchSearch && matchType && matchStatus;
  });

  // 状态统计（从物联网平台拉取）
  const statusStats = {
    total: components.length,
    online: components.filter(c => c.status === '在线').length,
    abnormal: components.filter(c => c.status === '异常').length,
    offline: components.filter(c => c.status === '离线').length,
  };

  // 类型统计
  const typeStats = {
    pump: components.filter(c => c.type === '泵体').length,
    sensor: components.filter(c => c.type === '传感器').length,
    controller: components.filter(c => c.type === '控制器').length,
    valve: components.filter(c => c.type === '阀门').length,
    flowmeter: components.filter(c => c.type === '流量计').length,
  };

  const getStatusColor = (status: ComponentStatus) => {
    switch (status) {
      case '在线': return 'bg-green-100 text-green-700 border-green-200';
      case '异常': return 'bg-yellow-100 text-yellow-700 border-yellow-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: ComponentStatus) => {
    switch (status) {
      case '在线': return <Wifi className="w-4 h-4" />;
      case '异常': return <AlertTriangle className="w-4 h-4" />;
      case '离线': return <WifiOff className="w-4 h-4" />;
      default: return <WifiOff className="w-4 h-4" />;
    }
  };

  // 新增部件
  const handleAdd = () => {
    setEditingComponent(null);
    setFormData({
      componentNo: `COMP-${new Date().getFullYear()}-${String(components.length + 1).padStart(3, '0')}`,
      linkedParameters: [],
    });
    setShowDialog(true);
  };

  // 编辑部件
  const handleEdit = (component: WFComponent) => {
    setEditingComponent(component);
    setFormData(component);
    setShowDialog(true);
  };

  // 查看详情
  const handleView = (component: WFComponent) => {
    setViewingComponent(component);
    setShowDetailDialog(true);
  };

  // 删除部件
  const handleDelete = (component: WFComponent) => {
    setDeleteTarget(component);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      setComponents(components.filter(c => c.id !== deleteTarget.id));
      toast.success(`部件 ${deleteTarget.componentName} 已删除`);
      setShowDeleteDialog(false);
      setDeleteTarget(null);
    }
  };

  // 保存部件
  const handleSave = () => {
    if (!formData.componentName || !formData.type) {
      toast.error('请填写必填项');
      return;
    }

    if (editingComponent) {
      // 更新 - 保留原有状态
      setComponents(components.map(c => 
        c.id === editingComponent.id ? { ...c, ...formData, status: c.status } as WFComponent : c
      ));
      toast.success('部件信息已更新');
    } else {
      // 新增 - 默认状态为"离线"（等待物联网平台上线）
      const newComponent: WFComponent = {
        ...formData,
        id: `comp-${Date.now()}`,
        status: '离线',
      } as WFComponent;
      setComponents([...components, newComponent]);
      toast.success('部件添加成功');
    }
    setShowDialog(false);
    setFormData({ linkedParameters: [] });
  };

  // 切换参数选择
  const toggleParameter = (parameterId: string) => {
    const currentParams = formData.linkedParameters || [];
    const newParams = currentParams.includes(parameterId)
      ? currentParams.filter(id => id !== parameterId)
      : [...currentParams, parameterId];
    setFormData({ ...formData, linkedParameters: newParams });
  };



  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">
          <Cpu 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>：从物联网平台实时拉取部件状态（在线/异常/离线）</li>
              <li>• <strong>完整CRUD</strong>：新增、编辑、查看、搜索、删除等全流程操作</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 统计卡片 - 物联网平台状态 */}
      <div className="grid grid-cols-1 md:grid-cols-4 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>
            <Package 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.online}</p>
            </div>
            <Wifi 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-yellow-600">{statusStats.abnormal}</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-yellow-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.offline}</p>
            </div>
            <WifiOff 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={filterType} onValueChange={setFilterType}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="部件类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="泵体">泵体</SelectItem>
                <SelectItem value="传感器">传感器</SelectItem>
                <SelectItem value="控制器">控制器</SelectItem>
                <SelectItem value="阀门">阀门</SelectItem>
                <SelectItem value="流量计">流量计</SelectItem>
                <SelectItem value="搅拌器">搅拌器</SelectItem>
                <SelectItem value="加热器">加热器</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="物联网状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="在线">在线</SelectItem>
                <SelectItem value="异常">异常</SelectItem>
                <SelectItem value="离线">离线</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 className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredComponents.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  <Package className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>暂无部件数据</p>
                </TableCell>
              </TableRow>
            ) : (
              filteredComponents.map((component) => (
                <TableRow key={component.id}>
                  <TableCell>
                    <div>
                      <div className="font-medium">{component.componentName}</div>
                      <div className="text-xs text-muted-foreground">#{component.componentNo}</div>
                      <div className="text-xs text-muted-foreground mt-1">{component.manufacturer}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{component.type}</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs space-y-1">
                      <div>量程: {component.range}</div>
                      <div>精度: {component.accuracy}</div>
                      {component.unit !== '-' && <div>单位: {component.unit}</div>}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {component.linkedParameters.length === 0 ? (
                        <span className="text-xs text-muted-foreground">未关联</span>
                      ) : (
                        <>
                          {component.linkedParameters.slice(0, 2).map(paramId => {
                            const param = availableParameters.find(p => p.id === paramId);
                            return param ? (
                              <Badge key={paramId} variant="outline" className="text-xs">
                                {param.parameterName}
                              </Badge>
                            ) : null;
                          })}
                          {component.linkedParameters.length > 2 && (
                            <Badge variant="outline" className="text-xs">
                              +{component.linkedParameters.length - 2}
                            </Badge>
                          )}
                        </>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={getStatusColor(component.status)}>
                      <span className="flex items-center gap-1">
                        {getStatusIcon(component.status)}
                        {component.status}
                      </span>
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2 justify-end">
                      <Button size="sm" variant="outline" onClick={() => handleView(component)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleEdit(component)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDelete(component)}
                        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-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingComponent ? '编辑部件信息' : '新增水肥机部件'}
            </DialogTitle>
            <DialogDescription>
              {editingComponent ? '修改部件配置信息' : '录入新部件配置信息'}
            </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.componentNo || ''}
                onChange={(e) => setFormData({ ...formData, componentNo: e.target.value })}
                placeholder="COMP-2024-001"
                disabled={!!editingComponent}
              />
            </div>

            <div>
              <Label>部件名称 *</Label>
              <Input
                value={formData.componentName || ''}
                onChange={(e) => setFormData({ ...formData, componentName: e.target.value })}
                placeholder="1号主水泵"
              />
            </div>

            <div className="col-span-2">
              <Label>部件类型 *</Label>
              <Select
                value={formData.type || ''}
                onValueChange={(value: ComponentType) => setFormData({ ...formData, type: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="请选择" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="泵体">泵体</SelectItem>
                  <SelectItem value="传感器">传感器</SelectItem>
                  <SelectItem value="控制器">控制器</SelectItem>
                  <SelectItem value="阀门">阀门</SelectItem>
                  <SelectItem value="流量计">流量计</SelectItem>
                  <SelectItem value="搅拌器">搅拌器</SelectItem>
                  <SelectItem value="加热器">加热器</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 参数关联 */}
            <div className="col-span-2 mt-4">
              <h4 className="mb-3 text-green-700 flex items-center gap-2">
                <Link2 className="w-4 h-4" />
                参数关联
              </h4>
            </div>

            <div className="col-span-2">
              <Label>选择关联参数</Label>
              <div className="mt-2 grid grid-cols-1 gap-2 max-h-60 overflow-y-auto border border-gray-200 rounded-md p-3">
                {availableParameters.map(param => (
                  <Card
                    key={param.id}
                    className={`p-3 cursor-pointer transition-colors ${
                      formData.linkedParameters?.includes(param.id)
                        ? 'border-green-500 bg-green-50'
                        : 'hover:border-green-300'
                    }`}
                    onClick={() => toggleParameter(param.id)}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <div className="text-sm">{param.parameterName}</div>
                          <Badge variant="outline" className="text-xs">{param.type}</Badge>
                        </div>
                        <div className="text-xs text-muted-foreground mt-1">
                          {param.description}
                        </div>
                        <div className="text-xs text-muted-foreground mt-1">
                          量程: {param.minValue}-{param.maxValue} {param.unit}
                        </div>
                      </div>
                      <div className="ml-4">
                        {formData.linkedParameters?.includes(param.id) ? (
                          <CheckCircle className="w-5 h-5 text-green-600" />
                        ) : (
                          <div className="w-5 h-5 border-2 border-gray-300 rounded-full" />
                        )}
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
              <div className="text-xs text-muted-foreground mt-2">
                已选择 {formData.linkedParameters?.length || 0} 个参数
              </div>
            </div>

            {/* 规格参数 */}
            <div className="col-span-2 mt-4">
              <h4 className="mb-3 text-green-700">规格参数</h4>
            </div>

            <div>
              <Label>规格型号</Label>
              <Input
                value={formData.specification || ''}
                onChange={(e) => setFormData({ ...formData, specification: e.target.value })}
                placeholder="1.5kW/220V"
              />
            </div>

            <div>
              <Label>制造商</Label>
              <Input
                value={formData.manufacturer || ''}
                onChange={(e) => setFormData({ ...formData, manufacturer: e.target.value })}
                placeholder="格兰富"
              />
            </div>

            <div>
              <Label>产品型号</Label>
              <Input
                value={formData.model || ''}
                onChange={(e) => setFormData({ ...formData, model: e.target.value })}
                placeholder="CR-15"
              />
            </div>

            <div>
              <Label>序列号</Label>
              <Input
                value={formData.serialNumber || ''}
                onChange={(e) => setFormData({ ...formData, serialNumber: e.target.value })}
                placeholder="GF20240315001"
              />
            </div>

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

            <div className="col-span-1"></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 max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>部件详细信息</DialogTitle>
            <DialogDescription>
              查看部件完整信息
            </DialogDescription>
          </DialogHeader>

          {viewingComponent && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <Package className="w-4 h-4" />
                  基本信息
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>部件编号</Label>
                    <div className="field-value">{viewingComponent.componentNo}</div>
                  </div>
                  <div>
                    <Label>部件名称</Label>
                    <div className="field-value">{viewingComponent.componentName}</div>
                  </div>
                  <div>
                    <Label>部件类型</Label>
                    <div className="mt-2">
                      <Badge variant="outline">{viewingComponent.type}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>物联网状态</Label>
                    <div className="mt-2">
                      <Badge className={getStatusColor(viewingComponent.status)}>
                        <span className="flex items-center gap-1">
                          {getStatusIcon(viewingComponent.status)}
                          {viewingComponent.status}
                        </span>
                      </Badge>
                    </div>
                  </div>
                </div>
              </div>

              {/* 规格参数 */}
              <div>
                <h4 className="mb-3 text-green-700">规格参数</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>规格型号</Label>
                    <div className="field-value">{viewingComponent.specification}</div>
                  </div>
                  <div>
                    <Label>制造商</Label>
                    <div className="field-value">{viewingComponent.manufacturer}</div>
                  </div>
                  <div>
                    <Label>产品型号</Label>
                    <div className="field-value">{viewingComponent.model}</div>
                  </div>
                  {viewingComponent.serialNumber && (
                    <div>
                      <Label>序列号</Label>
                      <div className="field-value font-mono">{viewingComponent.serialNumber}</div>
                    </div>
                  )}
                </div>
              </div>

              {/* 安装信息 */}
              <div>
                <h4 className="mb-3 text-green-700">安装信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>安装日期</Label>
                    <div className="field-value flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-muted-foreground" />
                      {viewingComponent.installDate}
                    </div>
                  </div>
                </div>
              </div>

              {/* 关联参数 */}
              <div>
                <h4 className="mb-3 text-green-700 flex items-center gap-2">
                  <Link2 className="w-4 h-4" />
                  关联参数
                </h4>
                {viewingComponent.linkedParameters.length === 0 ? (
                  <div className="text-sm text-muted-foreground">暂无关联参数</div>
                ) : (
                  <div className="grid grid-cols-1 gap-2">
                    {viewingComponent.linkedParameters.map(paramId => {
                      const param = availableParameters.find(p => p.id === paramId);
                      return param ? (
                        <Card key={paramId} className="p-3">
                          <div className="flex items-center justify-between">
                            <div>
                              <div className="font-medium text-sm">{param.parameterName}</div>
                              <div className="text-xs text-muted-foreground mt-1">
                                {param.description}
                              </div>
                            </div>
                            <div className="text-xs text-muted-foreground">
                              {param.minValue}-{param.maxValue} {param.unit}
                            </div>
                          </div>
                        </Card>
                      ) : null;
                    })}
                  </div>
                )}
              </div>

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

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

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700"
              onClick={() => {
                if (viewingComponent) {
                  setShowDetailDialog(false);
                  handleEdit(viewingComponent);
                }
              }}
            >
              <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?.componentName}</strong> (#{deleteTarget?.componentNo}) 吗？
              <br />
              <br />
              删除后将无法恢复，请谨慎操作。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction 
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
