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 { Checkbox } from '../ui/checkbox';
import {
  Search,
  Plus,
  Edit,
  Eye,
  Trash2,
  Link,
  CheckCircle,
  XCircle,
  AlertCircle,
  Settings,
  Server,
  Wifi,
  Activity,
  Zap,
  ChevronRight,
  ChevronLeft,
  Package,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

type ProtocolType = 'Modbus-RTU' | 'Modbus-TCP' | 'HTTP' | 'MQTT' | 'OPC-UA' | 'WebSocket';
type DataType = 'Boolean' | 'Int16' | 'Int32' | 'Float' | 'String';
type MappingStatus = '已映射' | '未映射' | '异常';
type ComponentType = '泵体' | '传感器' | '控制器' | '阀门' | '流量计' | '搅拌器' | '加热器';

// 水肥机设备接口
interface WFDevice {
  id: string;
  deviceNo: string;
  deviceName: string;
  model: string;
  manufacturer: string;
  ipAddress: string;
  port: number;
  protocol: ProtocolType;
  status: string;
}

// 水肥部件接口
interface WFComponent {
  id: string;
  componentNo: string;
  componentName: string;
  type: ComponentType;
  deviceNo: string;
  deviceName: string;
  specification: string;
}

// 部件映射信息
interface ComponentMapping {
  componentId: string;
  componentName: string;
  componentNo: string;
  componentType: ComponentType;
  controlPoint: string;
  readAddress: string;
  writeAddress: string;
  dataType: DataType;
  notes?: string;
}

// 点位配置接口
interface PointConfig {
  componentId: string;
  controlPoint: string;
  readAddress: string;
  writeAddress: string;
  dataType: DataType;
  notes: string;
}

// 设备映射接口 - 一个设备对应多个部件
interface DeviceMapping {
  id: string;
  mappingNo: string;
  deviceId: string;
  deviceName: string;
  deviceNo: string;
  deviceAddress: string;
  protocol: ProtocolType;
  components: ComponentMapping[]; // 多个部件
  status: MappingStatus;
  createdAt: string;
  updatedAt?: string;
}

export function WaterFertilizerMapping() {
  // 模拟水肥机设备数据
  const [devices] = useState<WFDevice[]>([
    {
      id: 'wfd-1',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      model: 'SF-3000Pro',
      manufacturer: '智农科技',
      ipAddress: '192.168.1.101',
      port: 502,
      protocol: 'Modbus-TCP',
      status: '正常',
    },
    {
      id: 'wfd-2',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      model: 'SF-2000',
      manufacturer: '绿地科技',
      ipAddress: '192.168.1.102',
      port: 502,
      protocol: 'Modbus-TCP',
      status: '正常',
    },
    {
      id: 'wfd-3',
      deviceNo: 'WF-2024-003',
      deviceName: '3号温室水肥控制器',
      model: 'SF-1500',
      manufacturer: '智农科技',
      ipAddress: '192.168.1.103',
      port: 502,
      protocol: 'Modbus-TCP',
      status: '停用',
    },
  ]);

  // 模拟水肥部件数据
  const [components] = useState<WFComponent[]>([
    // 1号设备的部件
    {
      id: 'comp-1',
      componentNo: 'COMP-001',
      componentName: '主水泵',
      type: '泵体',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      specification: 'CR-15',
    },
    {
      id: 'comp-2',
      componentNo: 'COMP-002',
      componentName: '主阀门',
      type: '阀门',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      specification: 'EV-DN25',
    },
    {
      id: 'comp-3',
      componentNo: 'COMP-003',
      componentName: 'EC传感器',
      type: '传感器',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      specification: 'EC-200Pro',
    },
    {
      id: 'comp-4',
      componentNo: 'COMP-004',
      componentName: 'PH传感器',
      type: '传感器',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      specification: 'PH-300Pro',
    },
    {
      id: 'comp-5',
      componentNo: 'COMP-005',
      componentName: '施肥泵A',
      type: '泵体',
      deviceNo: 'WF-2024-001',
      deviceName: '1号大棚水肥一体机',
      specification: 'FP-100',
    },
    // 2号设备的部件
    {
      id: 'comp-6',
      componentNo: 'COMP-006',
      componentName: '主水泵',
      type: '泵体',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      specification: 'CR-10',
    },
    {
      id: 'comp-7',
      componentNo: 'COMP-007',
      componentName: '电磁阀1',
      type: '阀门',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      specification: 'EV-DN20',
    },
    {
      id: 'comp-8',
      componentNo: 'COMP-008',
      componentName: '温度传感器',
      type: '传感器',
      deviceNo: 'WF-2024-002',
      deviceName: '2号田块智能水肥机',
      specification: 'T-500',
    },
    // 3号设备的部件
    {
      id: 'comp-9',
      componentNo: 'COMP-009',
      componentName: '主阀门',
      type: '阀门',
      deviceNo: 'WF-2024-003',
      deviceName: '3号温室水肥控制器',
      specification: 'EV-DN25',
    },
    {
      id: 'comp-10',
      componentNo: 'COMP-010',
      componentName: '流量计',
      type: '流量计',
      deviceNo: 'WF-2024-003',
      deviceName: '3号温室水肥控制器',
      specification: 'FM-100',
    },
  ]);

  const [mappings, setMappings] = useState<DeviceMapping[]>([
    {
      id: 'map-1',
      mappingNo: 'MAP-2024-001',
      deviceId: 'wfd-1',
      deviceName: '1号大棚水肥一体机',
      deviceNo: 'WF-2024-001',
      deviceAddress: '192.168.1.101:502',
      protocol: 'Modbus-TCP',
      components: [
        {
          componentId: 'comp-1',
          componentName: '主水泵',
          componentNo: 'COMP-001',
          componentType: '泵体',
          controlPoint: 'DO0',
          readAddress: '40001',
          writeAddress: '40001',
          dataType: 'Boolean',
          notes: '主水泵控制',
        },
        {
          componentId: 'comp-2',
          componentName: '主阀门',
          componentNo: 'COMP-002',
          componentType: '阀门',
          controlPoint: 'DO1',
          readAddress: '40002',
          writeAddress: '40002',
          dataType: 'Boolean',
          notes: '主管道阀门',
        },
        {
          componentId: 'comp-3',
          componentName: 'EC传感器',
          componentNo: 'COMP-003',
          componentType: '传感器',
          controlPoint: 'AI0',
          readAddress: '30001',
          writeAddress: '',
          dataType: 'Float',
          notes: 'EC值监测',
        },
      ],
      status: '已映射',
      createdAt: '2024-03-15',
    },
    {
      id: 'map-2',
      mappingNo: 'MAP-2024-002',
      deviceId: 'wfd-2',
      deviceName: '2号田块智能水肥机',
      deviceNo: 'WF-2024-002',
      deviceAddress: '192.168.1.102:502',
      protocol: 'Modbus-TCP',
      components: [
        {
          componentId: 'comp-6',
          componentName: '主水泵',
          componentNo: 'COMP-006',
          componentType: '泵体',
          controlPoint: 'DO0',
          readAddress: '40001',
          writeAddress: '40001',
          dataType: 'Boolean',
          notes: '2号设备主水泵',
        },
      ],
      status: '已映射',
      createdAt: '2024-05-20',
    },
  ]);

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [viewingMapping, setViewingMapping] = useState<DeviceMapping | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<DeviceMapping | null>(null);

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

  // 新增映射流程状态
  const [step, setStep] = useState(1); // 1=选择设备, 2=选择部件, 3=配置点位
  const [selectedDevice, setSelectedDevice] = useState<WFDevice | null>(null);
  const [selectedComponents, setSelectedComponents] = useState<string[]>([]);
  const [pointConfigs, setPointConfigs] = useState<Record<string, PointConfig>>({});

  // 过滤映射列表
  const filteredMappings = mappings.filter(mapping => {
    const matchSearch = searchText === '' || 
      mapping.deviceName.toLowerCase().includes(searchText.toLowerCase()) ||
      mapping.mappingNo.toLowerCase().includes(searchText.toLowerCase());
    
    const matchStatus = filterStatus === 'all' || mapping.status === filterStatus;
    const matchDevice = filterDevice === 'all' || mapping.deviceId === filterDevice;
    
    return matchSearch && matchStatus && matchDevice;
  });

  // 统计数据
  const stats = {
    total: mappings.length,
    mapped: mappings.filter(m => m.status === '已映射').length,
    unmapped: mappings.filter(m => m.status === '未映射').length,
    abnormal: mappings.filter(m => m.status === '异常').length,
    totalComponents: mappings.reduce((sum, m) => sum + m.components.length, 0),
  };

  const getStatusColor = (status: MappingStatus) => {
    switch (status) {
      case '已映射': return 'bg-green-100 text-green-700 border-green-200';
      case '未映射': return 'bg-gray-100 text-gray-700 border-gray-200';
      case '异常': return 'bg-red-100 text-red-700 border-red-200';
      default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const getStatusIcon = (status: MappingStatus) => {
    switch (status) {
      case '已映射': return <CheckCircle className="w-4 h-4" />;
      case '未映射': return <AlertCircle className="w-4 h-4" />;
      case '异常': return <XCircle className="w-4 h-4" />;
      default: return <AlertCircle className="w-4 h-4" />;
    }
  };

  const getTypeIcon = (type: ComponentType) => {
    switch (type) {
      case '阀门': return <Zap className="w-4 h-4" />;
      case '泵体': return <Activity className="w-4 h-4" />;
      case '传感器': return <Wifi className="w-4 h-4" />;
      default: return <Settings className="w-4 h-4" />;
    }
  };

  // 新增映射
  const handleAdd = () => {
    setStep(1);
    setSelectedDevice(null);
    setSelectedComponents([]);
    setPointConfigs({});
    setShowDialog(true);
  };

  // 查看详情
  const handleView = (mapping: DeviceMapping) => {
    setViewingMapping(mapping);
    setShowDetailDialog(true);
  };

  // 删除映射
  const handleDelete = (mapping: DeviceMapping) => {
    setDeleteTarget(mapping);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      setMappings(mappings.filter(m => m.id !== deleteTarget.id));
      toast.success(`映射 ${deleteTarget.deviceName} 已删除`);
      setShowDeleteDialog(false);
      setDeleteTarget(null);
    }
  };

  // 步骤1：选择设备
  const handleSelectDevice = (device: WFDevice) => {
    setSelectedDevice(device);
  };

  // 步骤2：切换部件选择
  const handleToggleComponent = (componentId: string) => {
    if (selectedComponents.includes(componentId)) {
      setSelectedComponents(selectedComponents.filter(id => id !== componentId));
      // 删除该部件的点位配置
      const newConfigs = { ...pointConfigs };
      delete newConfigs[componentId];
      setPointConfigs(newConfigs);
    } else {
      setSelectedComponents([...selectedComponents, componentId]);
      // 初始化该部件的点位配置
      setPointConfigs({
        ...pointConfigs,
        [componentId]: {
          componentId,
          controlPoint: '',
          readAddress: '',
          writeAddress: '',
          dataType: 'Boolean',
          notes: '',
        },
      });
    }
  };

  // 步骤3：更新点位配置
  const handleUpdatePointConfig = (componentId: string, field: keyof PointConfig, value: string) => {
    setPointConfigs({
      ...pointConfigs,
      [componentId]: {
        ...pointConfigs[componentId],
        [field]: value,
      },
    });
  };

  // 保存映射
  const handleSave = () => {
    if (!selectedDevice) {
      toast.error('请选择设备');
      return;
    }

    if (selectedComponents.length === 0) {
      toast.error('请至少选择一个部件');
      return;
    }

    // 验证所有选中部件都有点位配置
    for (const componentId of selectedComponents) {
      const config = pointConfigs[componentId];
      if (!config || !config.controlPoint) {
        const component = components.find(c => c.id === componentId);
        toast.error(`请配置部件 ${component?.componentName} 的点位信息`);
        return;
      }
    }

    // 创建部件映射列表
    const componentMappings: ComponentMapping[] = selectedComponents.map((componentId) => {
      const component = components.find(c => c.id === componentId)!;
      const config = pointConfigs[componentId];

      return {
        componentId: component.id,
        componentName: component.componentName,
        componentNo: component.componentNo,
        componentType: component.type,
        controlPoint: config.controlPoint,
        readAddress: config.readAddress,
        writeAddress: config.writeAddress,
        dataType: config.dataType as DataType,
        notes: config.notes,
      };
    });

    // 创建新的映射记录
    const mappingNo = `MAP-${new Date().getFullYear()}-${String(mappings.length + 1).padStart(3, '0')}`;
    const newMapping: DeviceMapping = {
      id: `map-${Date.now()}`,
      mappingNo,
      deviceId: selectedDevice.id,
      deviceName: selectedDevice.deviceName,
      deviceNo: selectedDevice.deviceNo,
      deviceAddress: `${selectedDevice.ipAddress}:${selectedDevice.port}`,
      protocol: selectedDevice.protocol,
      components: componentMappings,
      status: '未映射',
      createdAt: new Date().toISOString().split('T')[0],
    };

    setMappings([...mappings, newMapping]);
    toast.success(`成功创建映射配置，关联 ${componentMappings.length} 个部件`);
    setShowDialog(false);
  };

  // 获取当前设备的部件列表
  const getDeviceComponents = () => {
    if (!selectedDevice) return [];
    return components.filter(c => c.deviceNo === selectedDevice.deviceNo);
  };

  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">
          <Link 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>
            </ul>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 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">{stats.total}</p>
            </div>
            <Link 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">{stats.mapped}</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">{stats.unmapped}</p>
            </div>
            <AlertCircle className="w-12 h-12 text-gray-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-red-600">{stats.abnormal}</p>
            </div>
            <XCircle className="w-12 h-12 text-red-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-emerald-600">{stats.totalComponents}</p>
            </div>
            <Package className="w-12 h-12 text-emerald-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={filterDevice} onValueChange={setFilterDevice}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="选择设备" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部设备</SelectItem>
                {devices.map(device => (
                  <SelectItem key={device.id} value={device.id}>
                    {device.deviceName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-32">
                <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>
            {filteredMappings.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  <Link className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>暂无映射数据</p>
                </TableCell>
              </TableRow>
            ) : (
              filteredMappings.map((mapping) => (
                <TableRow key={mapping.id}>
                  <TableCell>
                    <div>
                      <div className="font-medium">{mapping.deviceName}</div>
                      <div className="text-xs text-muted-foreground mt-1">#{mapping.deviceNo}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Package className="w-4 h-4 text-blue-600" />
                      <span>已关联 {mapping.components.length} 个部件</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs space-y-1">
                      <div className="font-mono">{mapping.deviceAddress}</div>
                      <Badge variant="outline" className="text-xs">{mapping.protocol}</Badge>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={getStatusColor(mapping.status)}>
                      <span className="flex items-center gap-1">
                        {getStatusIcon(mapping.status)}
                        {mapping.status}
                      </span>
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-xs">{mapping.createdAt}</div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2 justify-end">
                      <Button size="sm" variant="outline" onClick={() => handleView(mapping)}>
                        <Eye className="w-3 h-3" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleDelete(mapping)}
                        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-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>新增设备映射</DialogTitle>
            <DialogDescription>
              {step === 1 && '步骤 1/3：选择水肥机设备'}
              {step === 2 && '步骤 2/3：选择需要映射的部件'}
              {step === 3 && '步骤 3/3：配置部件点位信息'}
            </DialogDescription>
          </DialogHeader>

          {/* 步骤指示器 */}
          <div className="flex items-center justify-center gap-4 py-4">
            <div className={`flex items-center gap-2 ${step >= 1 ? 'text-green-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 1 ? 'bg-green-600 text-white' : 'bg-gray-200'}`}>
                1
              </div>
              <span className="text-sm">选择设备</span>
            </div>
            <ChevronRight className="w-5 h-5 text-gray-400" />
            <div className={`flex items-center gap-2 ${step >= 2 ? 'text-green-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 2 ? 'bg-green-600 text-white' : 'bg-gray-200'}`}>
                2
              </div>
              <span className="text-sm">选择部件</span>
            </div>
            <ChevronRight className="w-5 h-5 text-gray-400" />
            <div className={`flex items-center gap-2 ${step >= 3 ? 'text-green-600' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 3 ? 'bg-green-600 text-white' : 'bg-gray-200'}`}>
                3
              </div>
              <span className="text-sm">配置点位</span>
            </div>
          </div>

          {/* 步骤1：选择设备 */}
          {step === 1 && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 gap-3">
                {devices.map(device => (
                  <Card
                    key={device.id}
                    className={`p-4 cursor-pointer transition-all ${
                      selectedDevice?.id === device.id
                        ? 'border-green-500 bg-green-50'
                        : 'hover:border-green-300'
                    }`}
                    onClick={() => handleSelectDevice(device)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Server className="w-10 h-10 text-green-600" />
                        <div>
                          <div className="font-medium">{device.deviceName}</div>
                          <div className="text-sm text-muted-foreground">
                            {device.deviceNo} | {device.model} | {device.manufacturer}
                          </div>
                          <div className="text-xs text-muted-foreground mt-1">
                            {device.ipAddress}:{device.port} | {device.protocol}
                          </div>
                        </div>
                      </div>
                      <div>
                        <Badge className={device.status === '正常' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
                          {device.status}
                        </Badge>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* 步骤2：选择部件 */}
          {step === 2 && selectedDevice && (
            <div className="space-y-4">
              <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                <div className="flex items-center gap-2">
                  <Server className="w-5 h-5 text-green-600" />
                  <span className="font-medium">{selectedDevice.deviceName}</span>
                  <Badge variant="outline">{selectedDevice.deviceNo}</Badge>
                </div>
              </div>

              <div className="space-y-2">
                {getDeviceComponents().map(component => (
                  <Card
                    key={component.id}
                    className={`p-4 cursor-pointer transition-all ${
                      selectedComponents.includes(component.id)
                        ? 'border-green-500 bg-green-50'
                        : 'hover:border-green-300'
                    }`}
                    onClick={() => handleToggleComponent(component.id)}
                  >
                    <div className="flex items-center gap-3">
                      <Checkbox
                        checked={selectedComponents.includes(component.id)}
                        onCheckedChange={() => handleToggleComponent(component.id)}
                      />
                      <Package className="w-8 h-8 text-blue-600" />
                      <div className="flex-1">
                        <div className="font-medium">{component.componentName}</div>
                        <div className="text-sm text-muted-foreground">
                          {component.componentNo} | {component.type} | {component.specification}
                        </div>
                      </div>
                      <Badge variant="outline">{component.type}</Badge>
                    </div>
                  </Card>
                ))}
              </div>

              {getDeviceComponents().length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  <Package className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>该设备暂无部件</p>
                </div>
              )}
            </div>
          )}

          {/* 步骤3：配置点位 */}
          {step === 3 && (
            <div className="space-y-6">
              <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                <div className="flex items-center gap-2">
                  <Server className="w-5 h-5 text-green-600" />
                  <span className="font-medium">{selectedDevice?.deviceName}</span>
                  <Badge variant="outline">已选择 {selectedComponents.length} 个部件</Badge>
                </div>
              </div>

              {selectedComponents.map(componentId => {
                const component = components.find(c => c.id === componentId)!;
                const config = pointConfigs[componentId] || {};

                return (
                  <Card key={componentId} className="p-4">
                    <div className="flex items-center gap-2 mb-4">
                      <Package className="w-5 h-5 text-blue-600" />
                      <span className="font-medium">{component.componentName}</span>
                      <Badge variant="outline">{component.type}</Badge>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>控制点位 *</Label>
                        <Input
                          value={config.controlPoint || ''}
                          onChange={(e) => handleUpdatePointConfig(componentId, 'controlPoint', e.target.value)}
                          placeholder="如：DO0、AO1、AI0"
                        />
                      </div>
                      <div>
                        <Label>数据类型 *</Label>
                        <Select
                          value={config.dataType || 'Boolean'}
                          onValueChange={(value) => handleUpdatePointConfig(componentId, 'dataType', value)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="Boolean">Boolean</SelectItem>
                            <SelectItem value="Int16">Int16</SelectItem>
                            <SelectItem value="Int32">Int32</SelectItem>
                            <SelectItem value="Float">Float</SelectItem>
                            <SelectItem value="String">String</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label>读地址</Label>
                        <Input
                          value={config.readAddress || ''}
                          onChange={(e) => handleUpdatePointConfig(componentId, 'readAddress', e.target.value)}
                          placeholder="如：40001"
                        />
                      </div>
                      <div>
                        <Label>写地址</Label>
                        <Input
                          value={config.writeAddress || ''}
                          onChange={(e) => handleUpdatePointConfig(componentId, 'writeAddress', e.target.value)}
                          placeholder="如：40001"
                        />
                      </div>
                      <div className="col-span-2">
                        <Label>备注</Label>
                        <Textarea
                          value={config.notes || ''}
                          onChange={(e) => handleUpdatePointConfig(componentId, 'notes', e.target.value)}
                          placeholder="选填：点位说明、注意事项等"
                          rows={2}
                        />
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          )}

          <DialogFooter>
            <div className="flex items-center justify-between w-full">
              <div>
                {step > 1 && (
                  <Button
                    variant="outline"
                    onClick={() => setStep(step - 1)}
                  >
                    <ChevronLeft className="w-4 h-4 mr-2" />
                    上一步
                  </Button>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowDialog(false)}>
                  取消
                </Button>
                {step < 3 ? (
                  <Button
                    className="bg-green-600 hover:bg-green-700"
                    onClick={() => {
                      if (step === 1 && !selectedDevice) {
                        toast.error('请选择一个设备');
                        return;
                      }
                      if (step === 2 && selectedComponents.length === 0) {
                        toast.error('请至少选择一个部件');
                        return;
                      }
                      setStep(step + 1);
                    }}
                  >
                    下一步
                    <ChevronRight className="w-4 h-4 ml-2" />
                  </Button>
                ) : (
                  <Button
                    className="bg-green-600 hover:bg-green-700"
                    onClick={handleSave}
                  >
                    完成并保存
                  </Button>
                )}
              </div>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>映射详情</DialogTitle>
            <DialogDescription>查看设备映射的详细信息</DialogDescription>
          </DialogHeader>

          {viewingMapping && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3 text-green-700">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>映射编号</Label>
                    <div className="field-value">{viewingMapping.mappingNo}</div>
                  </div>
                  <div>
                    <Label>创建时间</Label>
                    <div className="field-value">{viewingMapping.createdAt}</div>
                  </div>
                  <div>
                    <Label>水肥机设备</Label>
                    <div className="field-value">{viewingMapping.deviceName}</div>
                  </div>
                  <div>
                    <Label>设备编号</Label>
                    <div className="field-value">{viewingMapping.deviceNo}</div>
                  </div>
                  <div>
                    <Label>设备地址</Label>
                    <div className="field-value font-mono text-sm">{viewingMapping.deviceAddress}</div>
                  </div>
                  <div>
                    <Label>通信协议</Label>
                    <div className="field-value">
                      <Badge variant="outline">{viewingMapping.protocol}</Badge>
                    </div>
                  </div>
                  <div>
                    <Label>映射状态</Label>
                    <div className="field-value">
                      <Badge className={getStatusColor(viewingMapping.status)}>
                        <span className="flex items-center gap-1">
                          {getStatusIcon(viewingMapping.status)}
                          {viewingMapping.status}
                        </span>
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>关联部件数</Label>
                    <div className="field-value">{viewingMapping.components.length} 个部件</div>
                  </div>
                </div>
              </div>

              {/* 部件列表 */}
              <div>
                <h4 className="mb-3 text-green-700">关联部件列表</h4>
                <div className="space-y-3">
                  {viewingMapping.components.map((comp, index) => (
                    <Card key={index} className="p-4">
                      <div className="flex items-start gap-3">
                        <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex-shrink-0">
                          {index + 1}
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            {getTypeIcon(comp.componentType)}
                            <span className="font-medium">{comp.componentName}</span>
                            <Badge variant="outline" className="text-xs">{comp.componentType}</Badge>
                          </div>
                          <div className="grid grid-cols-3 gap-3 text-sm">
                            <div>
                              <div className="text-xs text-muted-foreground">部件编号</div>
                              <div className="mt-1">{comp.componentNo}</div>
                            </div>
                            <div>
                              <div className="text-xs text-muted-foreground">控制点位</div>
                              <div className="mt-1 font-mono">{comp.controlPoint}</div>
                            </div>
                            <div>
                              <div className="text-xs text-muted-foreground">数据类型</div>
                              <div className="mt-1">
                                <Badge variant="outline" className="text-xs">{comp.dataType}</Badge>
                              </div>
                            </div>
                            {comp.readAddress && (
                              <div>
                                <div className="text-xs text-muted-foreground">读地址</div>
                                <div className="mt-1 font-mono">{comp.readAddress}</div>
                              </div>
                            )}
                            {comp.writeAddress && (
                              <div>
                                <div className="text-xs text-muted-foreground">写地址</div>
                                <div className="mt-1 font-mono">{comp.writeAddress}</div>
                              </div>
                            )}
                          </div>
                          {comp.notes && (
                            <div className="mt-2 text-xs text-muted-foreground">
                              备注：{comp.notes}
                            </div>
                          )}
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除设备 <strong>{deleteTarget?.deviceName}</strong> 的映射配置吗？
              <div className="mt-2 text-sm">
                该映射包含 {deleteTarget?.components.length} 个部件，删除后无法恢复。
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
