import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { createFeiePrinterClient } from '../api/feiePrinterClient';
import {
  FeiePrinter,
  CreatePrinterRequest,
  UpdatePrinterRequest,
  PrinterQueryParams,
  PrinterListResponse,
  FeiePrintTask,
  PrintTaskQueryParams,
  PrintTaskListResponse,
  FeieConfig,
  ConfigListResponse,
  UpdateConfigRequest
} from '../types/feiePrinter';

/**
 * 飞鹅打印相关hooks
 */

interface UseFeiePrinterOptions {
  baseURL?: string;
  tenantId?: number;
  authToken?: string;
}

/**
 * 创建飞鹅打印客户端实例
 */
const useFeieClient = (options: UseFeiePrinterOptions) => {
  const { baseURL = '/api', tenantId, authToken } = options;
  const client = createFeiePrinterClient(baseURL);

  if (authToken) {
    client.setAuthToken(authToken);
  }
  if (tenantId) {
    client.setTenantId(tenantId);
  }

  return client;
};

/**
 * 使用打印机列表查询
 */
export const usePrinters = (
  params: PrinterQueryParams,
  options: UseFeiePrinterOptions & { enabled?: boolean } = {}
) => {
  const { enabled = true, ...clientOptions } = options;
  const client = useFeieClient(clientOptions);

  return useQuery<PrinterListResponse>({
    queryKey: ['printers', params, clientOptions.tenantId],
    queryFn: () => client.getPrinters(params),
    enabled: enabled && !!clientOptions.tenantId,
    staleTime: 5 * 60 * 1000, // 5分钟
    gcTime: 10 * 60 * 1000, // 10分钟
  });
};

/**
 * 使用添加打印机
 */
export const useAddPrinter = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<FeiePrinter, Error, CreatePrinterRequest>({
    mutationFn: (data) => client.addPrinter(data),
    onSuccess: () => {
      toast.success('打印机添加成功');
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error) => {
      toast.error(`添加打印机失败: ${error.message}`);
    }
  });
};

/**
 * 使用更新打印机
 */
export const useUpdatePrinter = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<FeiePrinter, Error, { printerSn: string; data: UpdatePrinterRequest }>({
    mutationFn: ({ printerSn, data }) => client.updatePrinter(printerSn, data),
    onSuccess: () => {
      toast.success('打印机更新成功');
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error) => {
      toast.error(`更新打印机失败: ${error.message}`);
    }
  });
};

/**
 * 使用删除打印机
 */
export const useDeletePrinter = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<void, Error, string>({
    mutationFn: (printerSn) => client.deletePrinter(printerSn),
    onSuccess: () => {
      toast.success('打印机删除成功');
      queryClient.invalidateQueries({ queryKey: ['printers'] });
    },
    onError: (error) => {
      toast.error(`删除打印机失败: ${error.message}`);
    }
  });
};

/**
 * 使用设置默认打印机
 */
export const useSetDefaultPrinter = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

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

/**
 * 使用打印任务列表查询
 */
export const usePrintTasks = (
  params: PrintTaskQueryParams,
  options: UseFeiePrinterOptions & { enabled?: boolean } = {}
) => {
  const { enabled = true, ...clientOptions } = options;
  const client = useFeieClient(clientOptions);

  return useQuery<PrintTaskListResponse>({
    queryKey: ['printTasks', params, clientOptions.tenantId],
    queryFn: () => client.getPrintTasks(params),
    enabled: enabled && !!clientOptions.tenantId,
    staleTime: 2 * 60 * 1000, // 2分钟（任务状态变化较快）
    gcTime: 5 * 60 * 1000, // 5分钟
  });
};

/**
 * 使用重试打印任务
 */
export const useRetryPrintTask = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<void, Error, number>({
    mutationFn: (taskId) => client.retryPrintTask(taskId),
    onSuccess: () => {
      toast.success('任务重试成功');
      queryClient.invalidateQueries({ queryKey: ['printTasks'] });
    },
    onError: (error) => {
      toast.error(`任务重试失败: ${error.message}`);
    }
  });
};

/**
 * 使用取消打印任务
 */
export const useCancelPrintTask = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<void, Error, { taskId: number; reason: string }>({
    mutationFn: ({ taskId, reason }) => client.cancelPrintTask(taskId, reason),
    onSuccess: () => {
      toast.success('任务取消成功');
      queryClient.invalidateQueries({ queryKey: ['printTasks'] });
    },
    onError: (error) => {
      toast.error(`任务取消失败: ${error.message}`);
    }
  });
};

/**
 * 使用打印配置列表查询
 */
export const usePrintConfigs = (
  options: UseFeiePrinterOptions & { enabled?: boolean } = {}
) => {
  const { enabled = true, ...clientOptions } = options;
  const client = useFeieClient(clientOptions);

  return useQuery<ConfigListResponse>({
    queryKey: ['printConfigs', clientOptions.tenantId],
    queryFn: () => client.getPrintConfigs(),
    enabled: enabled && !!clientOptions.tenantId,
    staleTime: 10 * 60 * 1000, // 10分钟（配置变化较慢）
    gcTime: 30 * 60 * 1000, // 30分钟
  });
};

/**
 * 使用更新打印配置
 */
export const useUpdatePrintConfig = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

  return useMutation<FeieConfig, Error, UpdateConfigRequest>({
    mutationFn: (data) => client.updatePrintConfig(data),
    onSuccess: () => {
      toast.success('配置更新成功');
      queryClient.invalidateQueries({ queryKey: ['printConfigs'] });
    },
    onError: (error) => {
      toast.error(`配置更新失败: ${error.message}`);
    }
  });
};

/**
 * 使用打印机状态刷新
 */
export const useRefreshPrinterStatus = (options: UseFeiePrinterOptions = {}) => {
  const queryClient = useQueryClient();
  const client = useFeieClient(options);

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