import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import {
  Plus,
  Search,
  Edit,
  Trash2,
  Printer,
  CheckCircle,
  XCircle,
  AlertCircle,
  Star,
  RefreshCw
} from 'lucide-react';

import {
  FeiePrinter,
  CreatePrinterRequest,
  UpdatePrinterRequest,
  PrinterStatus,
  PrinterType,
  PrinterQueryParams
} from '../types/feiePrinter';
import { createFeiePrinterClient } from '../api/feiePrinterClient';
import {
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Input,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Badge,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Switch,
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious
} from '@d8d/shared-ui-components';

// 创建打印机表单验证模式
const createPrinterSchema = z.object({
  printerSn: z.string().min(1, '打印机序列号不能为空'),
  printerKey: z.string().min(1, '打印机密钥不能为空'),
  printerName: z.string().optional(),
  printerType: z.nativeEnum(PrinterType).default(PrinterType.TYPE_58MM),
  isDefault: z.boolean().default(false)
});

type CreatePrinterFormValues = z.infer<typeof createPrinterSchema>;

// 更新打印机表单验证模式
const updatePrinterSchema = z.object({
  printerName: z.string().optional(),
  printerType: z.nativeEnum(PrinterType).optional(),
  printerStatus: z.nativeEnum(PrinterStatus).optional(),
  isDefault: z.boolean().optional()
});

type UpdatePrinterFormValues = z.infer<typeof updatePrinterSchema>;

// 打印机状态标签颜色映射
const statusColorMap: Record<PrinterStatus, string> = {
  [PrinterStatus.ACTIVE]: 'bg-green-100 text-green-800 border-green-200',
  [PrinterStatus.INACTIVE]: 'bg-gray-100 text-gray-800 border-gray-200',
  [PrinterStatus.ERROR]: 'bg-red-100 text-red-800 border-red-200'
};

// 打印机状态图标映射
const statusIconMap: Record<PrinterStatus, React.ReactNode> = {
  [PrinterStatus.ACTIVE]: <CheckCircle className="h-4 w-4 text-green-600" />,
  [PrinterStatus.INACTIVE]: <XCircle className="h-4 w-4 text-gray-600" />,
  [PrinterStatus.ERROR]: <AlertCircle className="h-4 w-4 text-red-600" />
};

// 打印机类型标签映射
const printerTypeLabelMap: Record<PrinterType, string> = {
  [PrinterType.TYPE_58MM]: '58mm',
  [PrinterType.TYPE_80MM]: '80mm'
};

interface PrinterManagementProps {
  /**
   * API基础URL
   * @default '/api'
   */
  baseURL?: string;
  /**
   * 租户ID
   */
  tenantId?: number;
  /**
   * 认证token
   */
  authToken?: string;
  /**
   * 每页显示数量
   * @default 10
   */
  pageSize?: number;
}

/**
 * 打印机管理组件
 * 提供打印机的添加、查询、删除、状态管理等功能
 */
export const PrinterManagement: React.FC<PrinterManagementProps> = ({
  baseURL = '/api',
  tenantId,
  authToken,
  pageSize = 10
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<PrinterStatus | 'ALL'>('ALL');
  const [printerTypeFilter, setPrinterTypeFilter] = useState<PrinterType | 'ALL'>('ALL');
  const [currentPage, setCurrentPage] = useState(1);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedPrinter, setSelectedPrinter] = useState<FeiePrinter | null>(null);

  const queryClient = useQueryClient();
  const feieClient = createFeiePrinterClient(baseURL);

  // 设置认证和租户信息
  useEffect(() => {
    if (authToken) {
      feieClient.setAuthToken(authToken);
    }
    if (tenantId) {
      feieClient.setTenantId(tenantId);
    }
  }, [authToken, tenantId, feieClient]);

  // 查询参数
  const queryParams: PrinterQueryParams = {
    page: currentPage,
    pageSize,
    search: searchQuery || undefined,
    status: statusFilter !== 'ALL' ? statusFilter : undefined,
    printerType: printerTypeFilter !== 'ALL' ? printerTypeFilter : undefined
  };

  // 查询打印机列表
  const {
    data: printerList,
    isLoading,
    isError,
    refetch
  } = useQuery({
    queryKey: ['printers', queryParams],
    queryFn: () => feieClient.getPrinters(queryParams),
    enabled: !!tenantId
  });

  // 创建打印机表单
  const createForm = useForm<CreatePrinterFormValues>({
    resolver: zodResolver(createPrinterSchema),
    defaultValues: {
      printerSn: '',
      printerKey: '',
      printerName: '',
      printerType: PrinterType.TYPE_58MM,
      isDefault: false
    }
  });

  // 更新打印机表单
  const updateForm = useForm<UpdatePrinterFormValues>({
    resolver: zodResolver(updatePrinterSchema),
    defaultValues: {
      printerName: '',
      printerType: PrinterType.TYPE_58MM,
      printerStatus: PrinterStatus.ACTIVE,
      isDefault: false
    }
  });

  // 添加打印机Mutation
  const addPrinterMutation = useMutation({
    mutationFn: (data: CreatePrinterRequest) => feieClient.addPrinter(data),
    onSuccess: () => {
      toast.success('打印机添加成功');
      setIsAddDialogOpen(false);
      createForm.reset();
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error: Error) => {
      toast.error(`添加打印机失败: ${error.message}`);
    }
  });

  // 更新打印机Mutation
  const updatePrinterMutation = useMutation({
    mutationFn: ({ printerSn, data }: { printerSn: string; data: UpdatePrinterRequest }) =>
      feieClient.updatePrinter(printerSn, data),
    onSuccess: () => {
      toast.success('打印机更新成功');
      setIsEditDialogOpen(false);
      setSelectedPrinter(null);
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error: Error) => {
      toast.error(`更新打印机失败: ${error.message}`);
    }
  });

  // 删除打印机Mutation
  const deletePrinterMutation = useMutation({
    mutationFn: (printerSn: string) => feieClient.deletePrinter(printerSn),
    onSuccess: () => {
      toast.success('打印机删除成功');
      setIsDeleteDialogOpen(false);
      setSelectedPrinter(null);
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error: Error) => {
      toast.error(`删除打印机失败: ${error.message}`);
    }
  });

  // 设置默认打印机Mutation
  const setDefaultPrinterMutation = useMutation({
    mutationFn: (printerSn: string) => feieClient.setDefaultPrinter(printerSn),
    onSuccess: () => {
      toast.success('默认打印机设置成功');
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error: Error) => {
      toast.error(`设置默认打印机失败: ${error.message}`);
    }
  });

  // 刷新打印机状态Mutation
  const refreshPrinterStatusMutation = useMutation({
    mutationFn: (printerSn: string) => feieClient.getPrinterStatus(printerSn),
    onSuccess: () => {
      toast.success('打印机状态刷新成功');
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error: Error) => {
      toast.error(`刷新打印机状态失败: ${error.message}`);
    }
  });

  // 处理添加打印机
  const handleAddPrinter = (data: CreatePrinterFormValues) => {
    addPrinterMutation.mutate(data);
  };

  // 处理更新打印机
  const handleUpdatePrinter = (data: UpdatePrinterFormValues) => {
    if (!selectedPrinter) return;
    updatePrinterMutation.mutate({
      printerSn: selectedPrinter.printerSn,
      data
    });
  };

  // 处理删除打印机
  const handleDeletePrinter = () => {
    if (!selectedPrinter) return;
    deletePrinterMutation.mutate(selectedPrinter.printerSn);
  };

  // 处理设置默认打印机
  const handleSetDefaultPrinter = (printerSn: string) => {
    setDefaultPrinterMutation.mutate(printerSn);
  };

  // 处理刷新打印机状态
  const handleRefreshPrinterStatus = (printerSn: string) => {
    refreshPrinterStatusMutation.mutate(printerSn);
  };

  // 打开编辑对话框
  const openEditDialog = (printer: FeiePrinter) => {
    setSelectedPrinter(printer);
    updateForm.reset({
      printerName: printer.printerName || '',
      printerType: printer.printerType,
      printerStatus: printer.printerStatus,
      isDefault: printer.isDefault
    });
    setIsEditDialogOpen(true);
  };

  // 打开删除对话框
  const openDeleteDialog = (printer: FeiePrinter) => {
    setSelectedPrinter(printer);
    setIsDeleteDialogOpen(true);
  };

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1);
    refetch();
  };

  // 处理重置筛选
  const handleResetFilters = () => {
    setSearchQuery('');
    setStatusFilter('ALL');
    setPrinterTypeFilter('ALL');
    setCurrentPage(1);
  };

  // 计算总页数
  const totalPages = printerList ? Math.ceil(printerList.total / pageSize) : 0;

  return (
    <div className="space-y-6">
      {/* 标题和操作栏 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">打印机管理</h2>
          <p className="text-muted-foreground">
            管理您的飞鹅打印机，支持添加、查询、删除和状态监控
          </p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              添加打印机
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>添加打印机</DialogTitle>
              <DialogDescription>
                填写打印机信息以添加新的打印机到系统
              </DialogDescription>
            </DialogHeader>
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleAddPrinter)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="printerSn"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>打印机序列号 *</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入打印机序列号" {...field} />
                      </FormControl>
                      <FormDescription>打印机的唯一序列号，可在打印机背面找到</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="printerKey"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>打印机密钥 *</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入打印机密钥" type="password" {...field} />
                      </FormControl>
                      <FormDescription>打印机的API密钥，用于身份验证</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="printerName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>打印机名称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入打印机名称（可选）" {...field} />
                      </FormControl>
                      <FormDescription>为打印机设置一个易于识别的名称</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="printerType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>打印机类型</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择打印机类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={PrinterType.TYPE_58MM}>58mm 小票打印机</SelectItem>
                          <SelectItem value={PrinterType.TYPE_80MM}>80mm 小票打印机</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormDescription>选择打印机的纸张宽度</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="isDefault"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">设为默认打印机</FormLabel>
                        <FormDescription>
                          将此打印机设置为默认打印机，用于自动打印任务
                        </FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <DialogFooter>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsAddDialogOpen(false)}
                    disabled={addPrinterMutation.isPending}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={addPrinterMutation.isPending}>
                    {addPrinterMutation.isPending ? '添加中...' : '添加打印机'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      {/* 筛选和搜索栏 */}
      <Card>
        <CardContent className="pt-6">
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Input
                  placeholder="搜索打印机名称或序列号..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full"
                />
              </div>
              <div>
                <Select value={statusFilter} onValueChange={(value) => setStatusFilter(value as any)}>
                  <SelectTrigger>
                    <SelectValue placeholder="筛选状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部状态</SelectItem>
                    <SelectItem value={PrinterStatus.ACTIVE}>正常</SelectItem>
                    <SelectItem value={PrinterStatus.INACTIVE}>停用</SelectItem>
                    <SelectItem value={PrinterStatus.ERROR}>错误</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Select value={printerTypeFilter} onValueChange={(value) => setPrinterTypeFilter(value as any)}>
                  <SelectTrigger>
                    <SelectValue placeholder="筛选类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部类型</SelectItem>
                    <SelectItem value={PrinterType.TYPE_58MM}>58mm</SelectItem>
                    <SelectItem value={PrinterType.TYPE_80MM}>80mm</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Button type="submit" size="sm">
                  <Search className="mr-2 h-4 w-4" />
                  搜索
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={handleResetFilters}
                >
                  重置筛选
                </Button>
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => refetch()}
                disabled={isLoading}
              >
                <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
                刷新
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>

      {/* 打印机列表 */}
      <Card>
        <CardHeader>
          <CardTitle>打印机列表</CardTitle>
          <CardDescription>
            共 {printerList?.total || 0} 台打印机，第 {currentPage} 页 / 共 {totalPages} 页
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <div className="text-center">
                <RefreshCw className="h-8 w-8 animate-spin mx-auto text-muted-foreground" />
                <p className="mt-2 text-sm text-muted-foreground">加载中...</p>
              </div>
            </div>
          ) : isError ? (
            <div className="flex items-center justify-center py-8">
              <div className="text-center">
                <AlertCircle className="h-8 w-8 mx-auto text-red-500" />
                <p className="mt-2 text-sm text-red-600">加载打印机列表失败</p>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-4"
                  onClick={() => refetch()}
                >
                  重试
                </Button>
              </div>
            </div>
          ) : printerList?.data.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Printer className="h-12 w-12 text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium">暂无打印机</h3>
              <p className="text-sm text-muted-foreground mt-2">
                {searchQuery || statusFilter !== 'ALL' || printerTypeFilter !== 'ALL'
                  ? '没有找到符合条件的打印机'
                  : '还没有添加任何打印机，点击"添加打印机"按钮开始添加'}
              </p>
            </div>
          ) : (
            <>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>序列号</TableHead>
                      <TableHead>名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>默认</TableHead>
                      <TableHead>创建时间</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {printerList?.data.map((printer) => (
                      <TableRow key={printer.id}>
                        <TableCell className="font-mono">{printer.printerSn}</TableCell>
                        <TableCell>
                          {printer.printerName || <span className="text-muted-foreground">未命名</span>}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">
                            {printerTypeLabelMap[printer.printerType]}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-2">
                            {statusIconMap[printer.printerStatus]}
                            <Badge
                              variant="outline"
                              className={statusColorMap[printer.printerStatus]}
                            >
                              {printer.printerStatus}
                            </Badge>
                          </div>
                        </TableCell>
                        <TableCell>
                          {printer.isDefault ? (
                            <Star className="h-5 w-5 text-yellow-500 fill-yellow-500" />
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {new Date(printer.createdAt).toLocaleDateString()}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end space-x-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleRefreshPrinterStatus(printer.printerSn)}
                              disabled={refreshPrinterStatusMutation.isPending}
                              title="刷新状态"
                            >
                              <RefreshCw className="h-4 w-4" />
                            </Button>
                            {!printer.isDefault && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleSetDefaultPrinter(printer.printerSn)}
                                disabled={setDefaultPrinterMutation.isPending}
                                title="设为默认"
                              >
                                <Star className="h-4 w-4" />
                              </Button>
                            )}
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openEditDialog(printer)}
                              title="编辑"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openDeleteDialog(printer)}
                              title="删除"
                            >
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 分页 */}
              {totalPages > 1 && (
                <div className="mt-4">
                  <Pagination>
                    <PaginationContent>
                      <PaginationItem>
                        <PaginationPrevious
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            if (currentPage > 1) setCurrentPage(currentPage - 1);
                          }}
                          className={currentPage === 1 ? 'pointer-events-none opacity-50' : ''}
                        />
                      </PaginationItem>
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum = i + 1;
                        if (currentPage > 3 && totalPages > 5) {
                          if (currentPage < totalPages - 2) {
                            pageNum = currentPage - 2 + i;
                          } else {
                            pageNum = totalPages - 4 + i;
                          }
                        }
                        return (
                          <PaginationItem key={pageNum}>
                            <PaginationLink
                              href="#"
                              onClick={(e) => {
                                e.preventDefault();
                                setCurrentPage(pageNum);
                              }}
                              isActive={currentPage === pageNum}
                            >
                              {pageNum}
                            </PaginationLink>
                          </PaginationItem>
                        );
                      })}
                      <PaginationItem>
                        <PaginationNext
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            if (currentPage < totalPages) setCurrentPage(currentPage + 1);
                          }}
                          className={currentPage === totalPages ? 'pointer-events-none opacity-50' : ''}
                        />
                      </PaginationItem>
                    </PaginationContent>
                  </Pagination>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* 编辑打印机对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>编辑打印机</DialogTitle>
            <DialogDescription>
              修改打印机信息
            </DialogDescription>
          </DialogHeader>
          <Form {...updateForm}>
            <form onSubmit={updateForm.handleSubmit(handleUpdatePrinter)} className="space-y-4">
              <FormField
                control={updateForm.control}
                name="printerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>打印机名称</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入打印机名称" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={updateForm.control}
                name="printerType"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>打印机类型</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择打印机类型" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value={PrinterType.TYPE_58MM}>58mm 小票打印机</SelectItem>
                        <SelectItem value={PrinterType.TYPE_80MM}>80mm 小票打印机</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={updateForm.control}
                name="printerStatus"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>打印机状态</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择打印机状态" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value={PrinterStatus.ACTIVE}>正常</SelectItem>
                        <SelectItem value={PrinterStatus.INACTIVE}>停用</SelectItem>
                        <SelectItem value={PrinterStatus.ERROR}>错误</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={updateForm.control}
                name="isDefault"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">设为默认打印机</FormLabel>
                      <FormDescription>
                        将此打印机设置为默认打印机，用于自动打印任务
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsEditDialogOpen(false)}
                  disabled={updatePrinterMutation.isPending}
                >
                  取消
                </Button>
                <Button type="submit" disabled={updatePrinterMutation.isPending}>
                  {updatePrinterMutation.isPending ? '更新中...' : '更新打印机'}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除打印机 "{selectedPrinter?.printerName || selectedPrinter?.printerSn}" 吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setIsDeleteDialogOpen(false)}
              disabled={deletePrinterMutation.isPending}
            >
              取消
            </Button>
            <Button
              type="button"
              variant="destructive"
              onClick={handleDeletePrinter}
              disabled={deletePrinterMutation.isPending}
            >
              {deletePrinterMutation.isPending ? '删除中...' : '确认删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};