import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import {
  Search,
  Eye,
  RefreshCw,
  XCircle,
  CheckCircle,
  Clock,
  AlertCircle,
  Calendar,
  Filter,
  Printer,
  Download
} from 'lucide-react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

import {
  FeiePrintTask,
  PrintTaskStatus,
  PrintTaskQueryParams,
  CancelReason
} from '../types/feiePrinter';
import { createFeiePrinterClient } from '../api/feiePrinterClient';

/**
 * 从JWT token中解析租户ID
 */
const parseTenantIdFromToken = (token?: string | null): number | undefined => {
  if (!token) return undefined;

  try {
    // JWT token格式: header.payload.signature
    const parts = token.split('.');
    if (parts.length !== 3) return undefined;

    // 解码payload部分
    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));

    // 从payload中获取tenantId
    // 可能是tenantId、tenant_id或tenant
    return payload.tenantId || payload.tenant_id || payload.tenant;
  } catch (error) {
    console.error('解析token失败:', error);
    return undefined;
  }
};
import {
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Input,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Badge,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  Popover,
  PopoverContent,
  PopoverTrigger,
  Calendar as CalendarComponent
} from '@d8d/shared-ui-components';

// 打印任务状态标签颜色映射
const taskStatusColorMap: Record<PrintTaskStatus, string> = {
  [PrintTaskStatus.PENDING]: 'bg-blue-100 text-blue-800 border-blue-200',
  [PrintTaskStatus.DELAYED]: 'bg-yellow-100 text-yellow-800 border-yellow-200',
  [PrintTaskStatus.PRINTING]: 'bg-purple-100 text-purple-800 border-purple-200',
  [PrintTaskStatus.SUCCESS]: 'bg-green-100 text-green-800 border-green-200',
  [PrintTaskStatus.FAILED]: 'bg-red-100 text-red-800 border-red-200',
  [PrintTaskStatus.CANCELLED]: 'bg-gray-100 text-gray-800 border-gray-200'
};

// 打印任务状态图标映射
const taskStatusIconMap: Record<PrintTaskStatus, React.ReactNode> = {
  [PrintTaskStatus.PENDING]: <Clock className="h-4 w-4 text-blue-600" />,
  [PrintTaskStatus.DELAYED]: <Clock className="h-4 w-4 text-yellow-600" />,
  [PrintTaskStatus.PRINTING]: <Printer className="h-4 w-4 text-purple-600" />,
  [PrintTaskStatus.SUCCESS]: <CheckCircle className="h-4 w-4 text-green-600" />,
  [PrintTaskStatus.FAILED]: <AlertCircle className="h-4 w-4 text-red-600" />,
  [PrintTaskStatus.CANCELLED]: <XCircle className="h-4 w-4 text-gray-600" />
};

// 打印任务状态标签映射
const taskStatusLabelMap: Record<PrintTaskStatus, string> = {
  [PrintTaskStatus.PENDING]: '待打印',
  [PrintTaskStatus.DELAYED]: '已延迟',
  [PrintTaskStatus.PRINTING]: '打印中',
  [PrintTaskStatus.SUCCESS]: '成功',
  [PrintTaskStatus.FAILED]: '失败',
  [PrintTaskStatus.CANCELLED]: '已取消'
};

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

/**
 * 打印任务查询组件
 * 提供打印任务的查询、详情查看、重试、取消等功能
 */
export const PrintTaskQuery: React.FC<PrintTaskQueryProps> = ({
  baseURL = '/api/v1/feie',
  tenantId: propTenantId,
  authToken: propAuthToken,
  pageSize = 10
}) => {
  // 从token中解析租户ID
  const token = propAuthToken || localStorage.getItem('token');
  const parsedTenantId = parseTenantIdFromToken(token);
  const tenantId = propTenantId || parsedTenantId;
  const authToken = propAuthToken || token;

  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<PrintTaskStatus | 'ALL'>('ALL');
  const [startDate, setStartDate] = useState<Date | undefined>();
  const [endDate, setEndDate] = useState<Date | undefined>();
  const [currentPage, setCurrentPage] = useState(1);
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState<FeiePrintTask | null>(null);
  const [isRetryDialogOpen, setIsRetryDialogOpen] = useState(false);
  const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);

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

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

  // 查询参数
  const queryParams: PrintTaskQueryParams = {
    page: currentPage,
    pageSize,
    status: statusFilter !== 'ALL' ? statusFilter : undefined,
    startDate: startDate ? format(startDate, 'yyyy-MM-dd') : undefined,
    endDate: endDate ? format(endDate, 'yyyy-MM-dd') : undefined,
    search: searchQuery.trim() || undefined
  };

  // 查询打印任务列表
  const {
    data: taskList,
    isLoading,
    isError,
    refetch
  } = useQuery({
    queryKey: ['printTasks', queryParams],
    queryFn: () => feieClient.getPrintTasks(queryParams),
    enabled: true // 总是启用查询，后端会从认证信息中获取租户ID
  });

  // 重试打印任务Mutation
  const retryTaskMutation = useMutation({
    mutationFn: (taskId: string) => feieClient.retryPrintTask({ taskId }),
    onSuccess: () => {
      toast.success('任务重试成功');
      setIsRetryDialogOpen(false);
      queryClient.invalidateQueries({ queryKey: ['printTasks'] });
    },
    onError: (error: Error) => {
      toast.error(`任务重试失败: ${error.message}`);
    }
  });

  // 取消打印任务Mutation
  const cancelTaskMutation = useMutation({
    mutationFn: ({ taskId, reason }: { taskId: string; reason: CancelReason }) =>
      feieClient.cancelPrintTask({ taskId, reason }),
    onSuccess: () => {
      toast.success('任务取消成功');
      setIsCancelDialogOpen(false);
      queryClient.invalidateQueries({ queryKey: ['printTasks'] });
    },
    onError: (error: Error) => {
      toast.error(`任务取消失败: ${error.message}`);
    }
  });

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

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

  // 打开详情对话框
  const openDetailDialog = (task: FeiePrintTask) => {
    setSelectedTask(task);
    setIsDetailDialogOpen(true);
  };

  // 打开重试对话框
  const openRetryDialog = (task: FeiePrintTask) => {
    setSelectedTask(task);
    setIsRetryDialogOpen(true);
  };

  // 打开取消对话框
  const openCancelDialog = (task: FeiePrintTask) => {
    setSelectedTask(task);
    setIsCancelDialogOpen(true);
  };

  // 处理重试任务
  const handleRetryTask = () => {
    if (!selectedTask) return;
    retryTaskMutation.mutate(selectedTask.taskId);
  };

  // 处理取消任务
  const handleCancelTask = (reason: CancelReason) => {
    if (!selectedTask) return;
    cancelTaskMutation.mutate({
      taskId: selectedTask.taskId,
      reason
    });
  };

  // 下载打印内容
  const handleDownloadContent = (task: FeiePrintTask) => {
    const blob = new Blob([task.content || ''], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `print-task-${task.taskId}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 计算总页数
  const totalPages = taskList ? Math.ceil(taskList.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>
        <Button
          variant="outline"
          onClick={() => refetch()}
          disabled={isLoading}
        >
          <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
          刷新
        </Button>
      </div>

      {/* 筛选和搜索栏 */}
      <Card>
        <CardContent className="pt-6">
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <Input
                  placeholder="搜索订单ID或任务ID..."
                  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={PrintTaskStatus.PENDING}>待打印</SelectItem>
                    <SelectItem value={PrintTaskStatus.DELAYED}>已延迟</SelectItem>
                    <SelectItem value={PrintTaskStatus.PRINTING}>打印中</SelectItem>
                    <SelectItem value={PrintTaskStatus.SUCCESS}>成功</SelectItem>
                    <SelectItem value={PrintTaskStatus.FAILED}>失败</SelectItem>
                    <SelectItem value={PrintTaskStatus.CANCELLED}>已取消</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button variant="outline" className="w-full justify-start text-left font-normal">
                      <Calendar className="mr-2 h-4 w-4" />
                      {startDate ? format(startDate, 'yyyy-MM-dd') : '开始日期'}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0">
                    <CalendarComponent
                      mode="single"
                      selected={startDate}
                      onSelect={setStartDate}
                      initialFocus
                      locale={zhCN}
                    />
                  </PopoverContent>
                </Popover>
              </div>
              <div>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button variant="outline" className="w-full justify-start text-left font-normal">
                      <Calendar className="mr-2 h-4 w-4" />
                      {endDate ? format(endDate, 'yyyy-MM-dd') : '结束日期'}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0">
                    <CalendarComponent
                      mode="single"
                      selected={endDate}
                      onSelect={setEndDate}
                      initialFocus
                      locale={zhCN}
                    />
                  </PopoverContent>
                </Popover>
              </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}
                >
                  <Filter className="mr-2 h-4 w-4" />
                  重置筛选
                </Button>
              </div>
              <div className="text-sm text-muted-foreground">
                共 {taskList?.total || 0} 条记录
              </div>
            </div>
          </form>
        </CardContent>
      </Card>

      {/* 打印任务列表 */}
      <Card>
        <CardHeader>
          <CardTitle>打印任务列表</CardTitle>
          <CardDescription>
            第 {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>
          ) : taskList?.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' || startDate || endDate
                  ? '没有找到符合条件的打印任务'
                  : '还没有打印任务记录'}
              </p>
            </div>
          ) : (
            <>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>任务ID</TableHead>
                      <TableHead>订单ID</TableHead>
                      <TableHead>打印机SN</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>创建时间</TableHead>
                      <TableHead>完成时间</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {taskList?.data.map((task) => (
                      <TableRow key={task.id}>
                        <TableCell className="font-mono">{task.taskId}</TableCell>
                        <TableCell>{task.orderId || '-'}</TableCell>
                        <TableCell className="font-mono">{task.printerSn}</TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-2">
                            {taskStatusIconMap[task.printStatus]}
                            <Badge
                              variant="outline"
                              className={taskStatusColorMap[task.printStatus]}
                            >
                              {taskStatusLabelMap[task.printStatus]}
                            </Badge>
                          </div>
                        </TableCell>
                        <TableCell>
                          {format(new Date(task.createdAt), 'yyyy-MM-dd HH:mm:ss')}
                        </TableCell>
                        <TableCell>
                          {task.printedAt || task.cancelledAt
                            ? format(new Date(task.printedAt || task.cancelledAt!), 'yyyy-MM-dd HH:mm:ss')
                            : '-'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end space-x-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openDetailDialog(task)}
                              title="查看详情"
                            >
                              <Eye className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDownloadContent(task)}
                              title="下载内容"
                            >
                              <Download className="h-4 w-4" />
                            </Button>
                            {task.printStatus === PrintTaskStatus.FAILED && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openRetryDialog(task)}
                                disabled={retryTaskMutation.isPending}
                                title="重试任务"
                              >
                                <RefreshCw className="h-4 w-4" />
                              </Button>
                            )}
                            {(task.printStatus === PrintTaskStatus.PENDING || task.printStatus === PrintTaskStatus.DELAYED) && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openCancelDialog(task)}
                                disabled={cancelTaskMutation.isPending}
                                title="取消任务"
                              >
                                <XCircle 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={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>打印任务详情</DialogTitle>
            <DialogDescription>
              任务ID: {selectedTask?.taskId}
            </DialogDescription>
          </DialogHeader>
          {selectedTask && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">订单ID</h4>
                  <p>{selectedTask.orderId || '-'}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">打印机SN</h4>
                  <p className="font-mono">{selectedTask.printerSn}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">状态</h4>
                  <div className="flex items-center space-x-2">
                    {taskStatusIconMap[selectedTask.printStatus]}
                    <Badge
                      variant="outline"
                      className={taskStatusColorMap[selectedTask.printStatus]}
                    >
                      {taskStatusLabelMap[selectedTask.printStatus]}
                    </Badge>
                  </div>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">重试次数</h4>
                  <p>{selectedTask.retryCount}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">创建时间</h4>
                  <p>{format(new Date(selectedTask.createdAt), 'yyyy-MM-dd HH:mm:ss')}</p>
                </div>
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">完成时间</h4>
                  <p>{selectedTask.printedAt || selectedTask.cancelledAt ? format(new Date(selectedTask.printedAt || selectedTask.cancelledAt!), 'yyyy-MM-dd HH:mm:ss') : '-'}</p>
                </div>
              </div>
              {selectedTask.errorMessage && (
                <div>
                  <h4 className="text-sm font-medium text-muted-foreground">错误信息</h4>
                  <div className="mt-1 p-3 bg-red-50 border border-red-200 rounded-md">
                    <p className="text-sm text-red-700">{selectedTask.errorMessage}</p>
                  </div>
                </div>
              )}
              <div>
                <h4 className="text-sm font-medium text-muted-foreground">打印内容</h4>
                <div className="mt-1 p-3 bg-gray-50 border border-gray-200 rounded-md font-mono text-sm whitespace-pre-wrap max-h-60 overflow-y-auto">
                  {selectedTask.content || '无内容'}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button onClick={() => setIsDetailDialogOpen(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 重试确认对话框 */}
      <Dialog open={isRetryDialogOpen} onOpenChange={setIsRetryDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>确认重试</DialogTitle>
            <DialogDescription>
              确定要重试任务 "{selectedTask?.taskId}" 吗？
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setIsRetryDialogOpen(false)}
              disabled={retryTaskMutation.isPending}
            >
              取消
            </Button>
            <Button
              type="button"
              onClick={handleRetryTask}
              disabled={retryTaskMutation.isPending}
            >
              {retryTaskMutation.isPending ? '重试中...' : '确认重试'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 取消确认对话框 */}
      <Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>取消打印任务</DialogTitle>
            <DialogDescription>
              确定要取消任务 "{selectedTask?.taskId}" 吗？请选择取消原因。
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => handleCancelTask(CancelReason.MANUAL)}
                disabled={cancelTaskMutation.isPending}
              >
                手动取消
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => handleCancelTask(CancelReason.REFUND)}
                disabled={cancelTaskMutation.isPending}
              >
                退款取消
              </Button>
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setIsCancelDialogOpen(false)}
              disabled={cancelTaskMutation.isPending}
            >
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};