import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Plus, Edit, Trash2, Eye, Search } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../../ui/alert-dialog';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { 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';
import { usePagination } from '../../../lib/usePagination';
import { DataPagination } from '../../ui/data-pagination';

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

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

export function LoadDeviceLibrary() {
  const [devices, setDevices] = useState<LoadDeviceRecord[]>([]);
  const [loadTypes, setLoadTypes] = useState<LoadType[]>([]);
  const [showDialog, setShowDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [editingDevice, setEditingDevice] = useState<LoadDeviceRecord | null>(null);
  const [viewingDevice, setViewingDevice] = useState<LoadDeviceRecord | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

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

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

  const loadData = () => {
    // 加载负载类型
    const typesData = localStorage.getItem('smart_agriculture_load_types');
    if (typesData) {
      const types = JSON.parse(typesData);
      // 确保所有类型都有parameterDefinitions字段
      const normalizedTypes = types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      }));
      setLoadTypes(normalizedTypes);
    } else {
      setLoadTypes([]);
    }

    // 加载负载设备
    const devicesData = localStorage.getItem('smart_agriculture_load_devices');
    if (devicesData) {
      setDevices(JSON.parse(devicesData));
    } else {
      // 初始化示例数据
      const mockDevices: LoadDeviceRecord[] = [
        {
          id: 'device-1',
          deviceName: '北斗定位终端-001',
          loadTypeId: 'type-1',
          purchaseDate: '2024-01-15',
          usageDate: '2024-01-20',
          remarks: '用于拖拉机实时定位',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-2',
          deviceName: '高清摄像头-A01',
          loadTypeId: 'type-2',
          purchaseDate: '2024-02-10',
          usageDate: '2024-02-15',
          remarks: '监控农田作业情况',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-3',
          deviceName: '油耗传感器-F01',
          loadTypeId: 'type-3',
          purchaseDate: '2024-03-05',
          remarks: '待安装',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem('smart_agriculture_load_devices', JSON.stringify(mockDevices));
      setDevices(mockDevices);
    }
  };

  const onSubmit = (data: any) => {
    if (editingDevice) {
      const updated: LoadDeviceRecord = {
        ...editingDevice,
        ...data,
        updatedAt: new Date().toISOString(),
      };
      const newDevices = devices.map(d => d.id === updated.id ? updated : d);
      setDevices(newDevices);
      localStorage.setItem('smart_agriculture_load_devices', JSON.stringify(newDevices));
      toast.success('设备更新成功');
    } else {
      const newDevice: LoadDeviceRecord = {
        id: `device-${Date.now()}`,
        ...data,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const newDevices = [...devices, newDevice];
      setDevices(newDevices);
      localStorage.setItem('smart_agriculture_load_devices', JSON.stringify(newDevices));
      toast.success('设备添加成功');
    }

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

  const handleEdit = (device: LoadDeviceRecord) => {
    setEditingDevice(device);
    setValue('deviceName', device.deviceName);
    setValue('loadTypeId', device.loadTypeId);
    setValue('purchaseDate', device.purchaseDate);
    setValue('usageDate', device.usageDate || '');
    setValue('remarks', device.remarks || '');
    setShowDialog(true);
  };

  const handleView = (device: LoadDeviceRecord) => {
    setViewingDevice(device);
    setShowViewDialog(true);
  };

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

  const confirmDelete = () => {
    if (pendingDeleteId) {
      const newDevices = devices.filter(d => d.id !== pendingDeleteId);
      setDevices(newDevices);
      localStorage.setItem('smart_agriculture_load_devices', JSON.stringify(newDevices));
      toast.success('设备删除成功');
    }
    setShowDeleteConfirm(false);
    setPendingDeleteId(null);
  };

  const getLoadTypeName = (typeId: string) => {
    const type = loadTypes.find(t => t.id === typeId);
    if (!type) return '未知类型';
    return `${type.name}${type.manufacturer ? ` (${type.manufacturer})` : ''}`;
  };

  const getLoadType = (typeId: string) => {
    return loadTypes.find(t => t.id === typeId);
  };

  // 搜索过滤
  const filteredDevices = devices.filter(device => {
    const searchLower = searchTerm.toLowerCase();
    return (
      device.deviceName.toLowerCase().includes(searchLower) ||
      getLoadTypeName(device.loadTypeId).toLowerCase().includes(searchLower) ||
      (device.remarks && device.remarks.toLowerCase().includes(searchLower))
    );
  });

  // 分页
  const {
    currentPage,
    pageSize,
    totalPages,
    paginatedData,
    handlePageChange,
    handlePageSizeChange,
  } = usePagination(filteredDevices, 10);

  // 统计
  const stats = {
    total: devices.length,
    withUsageDate: devices.filter(d => d.usageDate).length,
    withoutUsageDate: devices.filter(d => !d.usageDate).length,
    thisMonth: devices.filter(d => {
      const purchaseDate = new Date(d.purchaseDate);
      const now = new Date();
      return purchaseDate.getMonth() === now.getMonth() && 
             purchaseDate.getFullYear() === now.getFullYear();
    }).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>
        <Button 
          onClick={() => {
            setEditingDevice(null);
            reset();
            setShowDialog(true);
          }}
          className="bg-green-600 hover:bg-green-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          新增设备
        </Button>
      </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">{stats.total}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已投入使用</div>
          <div className="mt-1 text-green-600">{stats.withUsageDate}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待使用</div>
          <div className="mt-1 text-orange-600">{stats.withoutUsageDate}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">本月采购</div>
          <div className="mt-1 text-blue-600">{stats.thisMonth}</div>
        </Card>
      </div>

      {/* 搜索栏 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <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={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>
          {searchTerm && (
            <Button
              variant="outline"
              onClick={() => setSearchTerm('')}
            >
              清除
            </Button>
          )}
        </div>
      </Card>

      {/* 设备列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>设备名称</TableHead>
              <TableHead>负载类型</TableHead>
              <TableHead>采购时间</TableHead>
              <TableHead>使用时间</TableHead>
              <TableHead>备注</TableHead>
              <TableHead>状态</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  {searchTerm ? '未找到匹配的设备' : '暂无设备数据'}
                </TableCell>
              </TableRow>
            ) : (
              paginatedData.map((device) => (
                <TableRow key={device.id}>
                  <TableCell>{device.deviceName}</TableCell>
                  <TableCell>
                    <div className="flex flex-col">
                      <span>{getLoadTypeName(device.loadTypeId)}</span>
                      {getLoadType(device.loadTypeId)?.model && (
                        <span className="text-xs text-muted-foreground">
                          {getLoadType(device.loadTypeId)?.model}
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    {new Date(device.purchaseDate).toLocaleDateString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    {device.usageDate ? (
                      <span className="text-green-600">
                        {new Date(device.usageDate).toLocaleDateString('zh-CN')}
                      </span>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    {device.remarks ? (
                      <span className="text-sm" title={device.remarks}>
                        {device.remarks.length > 20 
                          ? `${device.remarks.substring(0, 20)}...` 
                          : device.remarks}
                      </span>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    {device.usageDate ? (
                      <Badge variant="secondary" className="bg-green-100 text-green-700">
                        已使用
                      </Badge>
                    ) : (
                      <Badge variant="secondary" className="bg-orange-100 text-orange-700">
                        待使用
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleView(device)}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(device)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick(device.id)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {/* 分页 */}
        {filteredDevices.length > 0 && (
          <DataPagination
            currentPage={currentPage}
            totalPages={totalPages}
            pageSize={pageSize}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            totalItems={filteredDevices.length}
          />
        )}
      </Card>

      {/* 添加/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingDevice ? '编辑设备' : '新增设备'}</DialogTitle>
            <DialogDescription>
              {editingDevice ? '修改设备信息' : '填写设备基本信息'}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="deviceName">
                    设备名称 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="deviceName"
                    {...register('deviceName', { required: true })}
                    placeholder="如：北斗定位终端-001"
                  />
                  {errors.deviceName && (
                    <p className="text-sm text-red-500">请输入设备名称</p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="loadTypeId">
                    负载类型 <span className="text-red-500">*</span>
                  </Label>
                  <Select
                    onValueChange={(value) => setValue('loadTypeId', value)}
                    defaultValue={editingDevice?.loadTypeId}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择负载类型" />
                    </SelectTrigger>
                    <SelectContent>
                      {loadTypes.length === 0 ? (
                        <SelectItem value="_none" disabled>
                          暂无可用类型
                        </SelectItem>
                      ) : (
                        loadTypes.map((type) => (
                          <SelectItem key={type.id} value={type.id}>
                            {type.name}
                            {type.manufacturer && ` (${type.manufacturer})`}
                            {type.model && ` - ${type.model}`}
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                  {errors.loadTypeId && (
                    <p className="text-sm text-red-500">请选择负载类型</p>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="purchaseDate">
                    采购时间 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="purchaseDate"
                    type="date"
                    {...register('purchaseDate', { required: true })}
                  />
                  {errors.purchaseDate && (
                    <p className="text-sm text-red-500">请选择采购时间</p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="usageDate">使用时间</Label>
                  <Input
                    id="usageDate"
                    type="date"
                    {...register('usageDate')}
                  />
                  <p className="text-xs text-muted-foreground">
                    留空表示待使用
                  </p>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="remarks">备注</Label>
                <Textarea
                  id="remarks"
                  {...register('remarks')}
                  rows={3}
                  placeholder="设备用途、注意事项等"
                />
              </div>
            </div>

            <DialogFooter className="mt-6">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  setShowDialog(false);
                  setEditingDevice(null);
                  reset();
                }}
              >
                取消
              </Button>
              <Button type="submit" className="bg-green-600 hover:bg-green-700">
                {editingDevice ? '保存' : '添加'}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent>
          <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">{viewingDevice.deviceName}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">负载类型</Label>
                  <p className="mt-1">{getLoadTypeName(viewingDevice.loadTypeId)}</p>
                </div>
              </div>

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

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

              <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                <div>
                  <Label className="text-muted-foreground">创建时间</Label>
                  <p className="mt-1 text-sm">
                    {new Date(viewingDevice.createdAt).toLocaleString('zh-CN')}
                  </p>
                </div>
                <div>
                  <Label className="text-muted-foreground">更新时间</Label>
                  <p className="mt-1 text-sm">
                    {new Date(viewingDevice.updatedAt).toLocaleString('zh-CN')}
                  </p>
                </div>
              </div>

              {getLoadType(viewingDevice.loadTypeId) && (
                <div className="pt-4 border-t">
                  <Label className="text-muted-foreground">类型详情</Label>
                  <div className="mt-2 space-y-2">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">
                        {getLoadType(viewingDevice.loadTypeId)?.name}
                      </Badge>
                      {getLoadType(viewingDevice.loadTypeId)?.manufacturer && (
                        <span className="text-sm text-muted-foreground">
                          {getLoadType(viewingDevice.loadTypeId)?.manufacturer}
                        </span>
                      )}
                      {getLoadType(viewingDevice.loadTypeId)?.model && (
                        <span className="text-sm text-muted-foreground">
                          {getLoadType(viewingDevice.loadTypeId)?.model}
                        </span>
                      )}
                    </div>
                    {getLoadType(viewingDevice.loadTypeId)?.description && (
                      <p className="text-sm text-muted-foreground">
                        {getLoadType(viewingDevice.loadTypeId)?.description}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

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

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除此设备吗？此操作不可恢复。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setPendingDeleteId(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
