import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Plus, Link2, Unlink, History, Eye } from 'lucide-react';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Textarea } from '../../ui/textarea';
import { toast } from 'sonner@2.0.3';
import { useForm } from 'react-hook-form@7.55.0';

// 负载设备接口（来自设备库）
interface LoadDeviceRecord {
  id: string;
  deviceName: string;
  loadTypeId: string;
  purchaseDate: string;
  usageDate?: string;
  remarks?: string;
  createdAt: string;
  updatedAt: string;
}

// 负载类型接口
interface LoadType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions?: any[];
}

// 挂载记录接口
interface MountedDeviceRecord {
  id: string;
  machineryId: string;
  deviceId: string; // 关联负载设备库
  mountedAt: string;
  unmountedAt?: string;
  status: 'mounted' | 'unmounted';
  remarks?: string;
  operator: string;
  createdAt: string;
  updatedAt: string;
}

export function LoadDevice() {
  const [mountedDevices, setMountedDevices] = useState<MountedDeviceRecord[]>([]);
  const [loadDevices, setLoadDevices] = useState<LoadDeviceRecord[]>([]);
  const [loadTypes, setLoadTypes] = useState<LoadType[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [showMountDialog, setShowMountDialog] = useState(false);
  const [selectedMachinery, setSelectedMachinery] = useState<string>('');
  const [showUnmountConfirm, setShowUnmountConfirm] = useState(false);
  const [pendingUnmountId, setPendingUnmountId] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<'mounted' | 'unmounted'>('mounted');
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [viewingDevice, setViewingDevice] = useState<MountedDeviceRecord | null>(null);

  const { handleSubmit, setValue, reset } = useForm();

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

  const loadData = () => {
    setMachinery(machineryStorage.getAllMachinery());
    
    // 加载负载类型
    const typesData = localStorage.getItem('smart_agriculture_load_types');
    if (typesData) {
      const types = JSON.parse(typesData);
      setLoadTypes(types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      })));
    }

    // 加载负载设备库
    const devicesData = localStorage.getItem('smart_agriculture_load_devices');
    if (devicesData) {
      setLoadDevices(JSON.parse(devicesData));
    }

    // 加载挂载记录
    const mountedData = localStorage.getItem('smart_agriculture_mounted_devices');
    if (mountedData) {
      setMountedDevices(JSON.parse(mountedData));
    } else {
      // 初始化示例数据
      const mockMounted: MountedDeviceRecord[] = [
        {
          id: 'mounted-1',
          machineryId: machinery[0]?.id || 'machinery-1',
          deviceId: 'device-1',
          mountedAt: '2024-01-20T08:00:00',
          status: 'mounted',
          remarks: '用于实时定位',
          operator: '技术员张三',
          createdAt: '2024-01-20T08:00:00',
          updatedAt: '2024-01-20T08:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_mounted_devices', JSON.stringify(mockMounted));
      setMountedDevices(mockMounted);
    }
  };

  const onMountDevice = (data: any) => {
    const newMounted: MountedDeviceRecord = {
      id: `mounted-${Date.now()}`,
      machineryId: selectedMachinery,
      deviceId: data.deviceId,
      mountedAt: new Date().toISOString(),
      status: 'mounted',
      remarks: data.remarks,
      operator: '系统管理员',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    const newMountedDevices = [...mountedDevices, newMounted];
    setMountedDevices(newMountedDevices);
    localStorage.setItem('smart_agriculture_mounted_devices', JSON.stringify(newMountedDevices));
    toast.success('设备挂载成功');
    setShowMountDialog(false);
    reset();
  };

  const handleUnmountClick = (mountedId: string) => {
    setPendingUnmountId(mountedId);
    setShowUnmountConfirm(true);
  };

  const confirmUnmount = () => {
    if (pendingUnmountId) {
      const updatedMounted = mountedDevices.map(d => {
        if (d.id === pendingUnmountId && d.status === 'mounted') {
          return {
            ...d,
            status: 'unmounted' as const,
            unmountedAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          };
        }
        return d;
      });

      setMountedDevices(updatedMounted);
      localStorage.setItem('smart_agriculture_mounted_devices', JSON.stringify(updatedMounted));
      toast.success('设备卸载成功');
    }
    setShowUnmountConfirm(false);
    setPendingUnmountId(null);
  };

  const handleViewDetails = (mounted: MountedDeviceRecord) => {
    setViewingDevice(mounted);
    setShowDetailsDialog(true);
  };

  const getMachineryMountedDevices = (machineryId: string, status: 'mounted' | 'unmounted') => {
    return mountedDevices.filter(d => d.machineryId === machineryId && d.status === status);
  };

  const getDevice = (deviceId: string) => {
    return loadDevices.find(d => d.id === deviceId);
  };

  const getDeviceName = (deviceId: string) => {
    const device = getDevice(deviceId);
    return device?.deviceName || '未知设备';
  };

  const getDeviceType = (deviceId: string) => {
    const device = getDevice(deviceId);
    if (!device) return null;
    return loadTypes.find(t => t.id === device.loadTypeId);
  };

  const getDeviceTypeName = (deviceId: string) => {
    const type = getDeviceType(deviceId);
    if (!type) return '未知类型';
    return `${type.name}${type.manufacturer ? ` (${type.manufacturer})` : ''}`;
  };

  // 获取可挂载的设备（未被当前农机挂载的设备）
  const getAvailableDevices = (machineryId: string) => {
    const currentMounted = mountedDevices
      .filter(m => m.machineryId === machineryId && m.status === 'mounted')
      .map(m => m.deviceId);
    
    return loadDevices.filter(d => !currentMounted.includes(d.id));
  };

  const renderDeviceList = (status: 'mounted' | 'unmounted') => {
    return machinery.map(m => {
      const machineryDevices = getMachineryMountedDevices(m.id, status);
      
      return (
        <Card key={m.id} className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3>{m.name}</h3>
              <p className="text-sm text-muted-foreground">{m.model}</p>
            </div>
            <div className="flex gap-2">
              <Badge variant="outline">
                {machineryDevices.length} 个设备
              </Badge>
              {status === 'mounted' && (
                <Button
                  size="sm"
                  onClick={() => {
                    setSelectedMachinery(m.id);
                    setShowMountDialog(true);
                  }}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  挂载设备
                </Button>
              )}
            </div>
          </div>

          {machineryDevices.length === 0 ? (
            <div className="text-center text-muted-foreground py-8 border-2 border-dashed rounded-lg">
              {status === 'mounted' ? '暂无挂载设备' : '暂无卸载记录'}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>设备名称</TableHead>
                  <TableHead>设备类型</TableHead>
                  <TableHead>挂载时间</TableHead>
                  {status === 'unmounted' && <TableHead className="text-red-600">卸载时间</TableHead>}
                  <TableHead>操作员</TableHead>
                  <TableHead>备注</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {machineryDevices.map(mounted => (
                  <TableRow key={mounted.id}>
                    <TableCell>
                      <div className="flex flex-col">
                        <span>{getDeviceName(mounted.deviceId)}</span>
                        {getDevice(mounted.deviceId)?.purchaseDate && (
                          <span className="text-xs text-muted-foreground">
                            采购: {new Date(getDevice(mounted.deviceId)!.purchaseDate).toLocaleDateString('zh-CN')}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span>{getDeviceTypeName(mounted.deviceId)}</span>
                        {getDeviceType(mounted.deviceId)?.model && (
                          <span className="text-xs text-muted-foreground">
                            {getDeviceType(mounted.deviceId)?.model}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      {new Date(mounted.mountedAt).toLocaleString('zh-CN')}
                    </TableCell>
                    {status === 'unmounted' && (
                      <TableCell>
                        <span className="text-red-600">
                          {mounted.unmountedAt 
                            ? new Date(mounted.unmountedAt).toLocaleString('zh-CN')
                            : '-'}
                        </span>
                      </TableCell>
                    )}
                    <TableCell>{mounted.operator}</TableCell>
                    <TableCell>
                      {mounted.remarks ? (
                        <span className="text-sm" title={mounted.remarks}>
                          {mounted.remarks.length > 15 
                            ? `${mounted.remarks.substring(0, 15)}...` 
                            : mounted.remarks}
                        </span>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {status === 'mounted' ? (
                        <Badge variant="secondary" className="bg-green-100 text-green-700">
                          已挂载
                        </Badge>
                      ) : (
                        <Badge variant="secondary" className="bg-gray-100 text-gray-700">
                          已卸载
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewDetails(mounted)}
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                        {status === 'mounted' && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUnmountClick(mounted.id)}
                            className="text-red-600 hover:text-red-700"
                          >
                            <Unlink className="w-4 h-4" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </Card>
      );
    });
  };

  const stats = {
    totalMounted: mountedDevices.filter(d => d.status === 'mounted').length,
    totalUnmounted: mountedDevices.filter(d => d.status === 'unmounted').length,
    totalDevices: loadDevices.length,
    availableDevices: loadDevices.length - mountedDevices.filter(d => d.status === 'mounted').length,
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">负载管理</h2>
          <p className="text-muted-foreground">管理农机挂载设备的添加、移除和状态</p>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总挂载数</div>
          <div className="mt-1 text-green-600">{stats.totalMounted}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已卸载</div>
          <div className="mt-1 text-gray-600">{stats.totalUnmounted}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">设备库总数</div>
          <div className="mt-1">{stats.totalDevices}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">可挂载设备</div>
          <div className="mt-1 text-blue-600">{stats.availableDevices}</div>
        </Card>
      </div>

      {/* 切换视图 */}
      <Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'mounted' | 'unmounted')} className="space-y-4">
        <TabsList>
          <TabsTrigger value="mounted" className="flex items-center gap-2">
            <Link2 className="w-4 h-4" />
            已挂载设备
          </TabsTrigger>
          <TabsTrigger value="unmounted" className="flex items-center gap-2">
            <History className="w-4 h-4" />
            卸载历史
          </TabsTrigger>
        </TabsList>

        <TabsContent value="mounted">
          {renderDeviceList('mounted')}
        </TabsContent>

        <TabsContent value="unmounted">
          {renderDeviceList('unmounted')}
        </TabsContent>
      </Tabs>

      {/* 挂载设备对话框 */}
      <Dialog open={showMountDialog} onOpenChange={setShowMountDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>挂载设备</DialogTitle>
            <DialogDescription>
              从设备库中选择设备挂载到农机上
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onMountDevice)}>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>
                  选择设备 <span className="text-red-500">*</span>
                </Label>
                <Select onValueChange={(value) => setValue('deviceId', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="从设备库选择设备" />
                  </SelectTrigger>
                  <SelectContent>
                    {getAvailableDevices(selectedMachinery).length === 0 ? (
                      <SelectItem value="_none" disabled>
                        暂无可挂载设备
                      </SelectItem>
                    ) : (
                      getAvailableDevices(selectedMachinery).map(device => {
                        const type = loadTypes.find(t => t.id === device.loadTypeId);
                        return (
                          <SelectItem key={device.id} value={device.id}>
                            <div className="flex flex-col">
                              <span>{device.deviceName}</span>
                              <span className="text-xs text-muted-foreground">
                                {type?.name}{type?.manufacturer && ` (${type.manufacturer})`}
                                {type?.model && ` - ${type.model}`}
                              </span>
                            </div>
                          </SelectItem>
                        );
                      })
                    )}
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground">
                  只显示设备库中未被当前农机挂载的设备
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="remarks">备注</Label>
                <Textarea 
                  id="remarks" 
                  onChange={(e) => setValue('remarks', e.target.value)}
                  rows={3}
                  placeholder="挂载说明、注意事项等"
                />
              </div>
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="outline" onClick={() => setShowMountDialog(false)}>
                取消
              </Button>
              <Button type="submit" className="bg-green-600 hover:bg-green-700">
                <Link2 className="w-4 h-4 mr-2" />
                挂载
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>挂载详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看设备挂载详细信息
            </DialogDescription>
          </DialogHeader>

          {viewingDevice && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">设备名称</Label>
                  <p className="mt-1">{getDeviceName(viewingDevice.deviceId)}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">设备类型</Label>
                  <p className="mt-1">{getDeviceTypeName(viewingDevice.deviceId)}</p>
                </div>
              </div>

              {getDeviceType(viewingDevice.deviceId) && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-muted-foreground">品牌</Label>
                    <p className="mt-1">{getDeviceType(viewingDevice.deviceId)?.manufacturer || '-'}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">型号</Label>
                    <p className="mt-1">{getDeviceType(viewingDevice.deviceId)?.model || '-'}</p>
                  </div>
                </div>
              )}

              {getDevice(viewingDevice.deviceId) && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-muted-foreground">采购时间</Label>
                    <p className="mt-1">
                      {new Date(getDevice(viewingDevice.deviceId)!.purchaseDate).toLocaleDateString('zh-CN')}
                    </p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">设备使用时间</Label>
                    <p className="mt-1">
                      {getDevice(viewingDevice.deviceId)?.usageDate 
                        ? new Date(getDevice(viewingDevice.deviceId)!.usageDate!).toLocaleDateString('zh-CN')
                        : '-'}
                    </p>
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                <div>
                  <Label className="text-muted-foreground">挂载时间</Label>
                  <p className="mt-1">{new Date(viewingDevice.mountedAt).toLocaleString('zh-CN')}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">挂载状态</Label>
                  <div className="mt-1">
                    {viewingDevice.status === 'mounted' ? (
                      <Badge className="bg-green-100 text-green-700">已挂载</Badge>
                    ) : (
                      <Badge className="bg-gray-100 text-gray-700">已卸载</Badge>
                    )}
                  </div>
                </div>
              </div>

              {viewingDevice.status === 'unmounted' && viewingDevice.unmountedAt && (
                <div>
                  <Label className="text-muted-foreground">卸载时间</Label>
                  <p className="mt-1 text-red-600">
                    {new Date(viewingDevice.unmountedAt).toLocaleString('zh-CN')}
                  </p>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">操作员</Label>
                  <p className="mt-1">{viewingDevice.operator}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">创建时间</Label>
                  <p className="mt-1 text-sm">
                    {new Date(viewingDevice.createdAt).toLocaleString('zh-CN')}
                  </p>
                </div>
              </div>

              {viewingDevice.remarks && (
                <div className="pt-4 border-t">
                  <Label className="text-muted-foreground">备注</Label>
                  <p className="mt-1 text-sm bg-muted p-3 rounded">
                    {viewingDevice.remarks}
                  </p>
                </div>
              )}

              {getDevice(viewingDevice.deviceId)?.remarks && (
                <div className="pt-4 border-t">
                  <Label className="text-muted-foreground">设备备注</Label>
                  <p className="mt-1 text-sm bg-muted p-3 rounded">
                    {getDevice(viewingDevice.deviceId)?.remarks}
                  </p>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setShowDetailsDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 卸载设备确认对话框 */}
      <AlertDialog open={showUnmountConfirm} onOpenChange={setShowUnmountConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认卸载设备</AlertDialogTitle>
            <AlertDialogDescription>
              确定要卸载此设备吗？卸载后设备状态将变为"已卸载"，可以重新挂载到其他农机上。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setPendingUnmountId(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmUnmount} className="bg-red-600 hover:bg-red-700">
              确认卸载
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
