import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { PrintTaskQuery } from '../../src/components/PrintTaskQuery';
import { createFeiePrinterClient } from '../../src/api/feiePrinterClient';
import { PrintTaskStatus, CancelReason } from '../../src/types/feiePrinter';

// Mock API client
vi.mock('../../src/api/feiePrinterClient', () => {
  const mockClient = {
    getPrintTasks: vi.fn(),
    getPrintTask: vi.fn(),
    retryPrintTask: vi.fn(),
    cancelPrintTask: vi.fn(),
    setAuthToken: vi.fn(),
    setTenantId: vi.fn(),
  };

  return {
    createFeiePrinterClient: vi.fn(() => mockClient),
  };
});

// Mock toast
vi.mock('sonner', () => ({
  toast: {
    success: vi.fn(() => {}),
    error: vi.fn(() => {}),
    info: vi.fn(() => {}),
  },
}));

// Mock date-fns format
vi.mock('date-fns', () => ({
  format: vi.fn(() => '2024-01-01 10:00:00'),
}));

const createTestQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  });

const renderWithProviders = (component: React.ReactElement) => {
  const queryClient = createTestQueryClient();
  return render(
    <QueryClientProvider client={queryClient}>
      {component as any}
    </QueryClientProvider>
  );
};

describe('打印任务查询组件简化集成测试', () => {
  let mockClient: any;

  beforeEach(() => {
    vi.clearAllMocks();
    mockClient = (createFeiePrinterClient as any)();
  });

  it('应该正确渲染组件并加载数据', async () => {
    const mockTasksData = {
      data: [
        {
          id: 1,
          taskId: 'TASK001',
          orderId: 1001,
          printerSn: 'SN001',
          content: '订单号: 1001\n商品: 商品A x 2\n合计: ¥100.00',
          printType: 'RECEIPT',
          printStatus: PrintTaskStatus.SUCCESS,
          errorMessage: null,
          retryCount: 0,
          maxRetries: 3,
          scheduledAt: '2024-01-01T10:00:00Z',
          printedAt: '2024-01-01T10:00:05Z',
          cancelledAt: null,
          cancelReason: null,
          createdAt: '2024-01-01T10:00:00Z',
          updatedAt: '2024-01-01T10:00:05Z',
          tenantId: 123,
        },
      ],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
        totalPages: 1,
      },
    };

    mockClient.getPrintTasks.mockResolvedValue(mockTasksData);

    renderWithProviders(
      <PrintTaskQuery
        baseURL="/api/v1/feie"
        tenantId={123}
        authToken="test-token"
      />
    );

    // 验证API调用
    await waitFor(() => {
      expect(mockClient.getPrintTasks).toHaveBeenCalledWith({
        page: 1,
        pageSize: 10,
      });
    });

    // 验证组件标题
    expect(screen.getByText('打印任务查询')).toBeInTheDocument();

    // 验证搜索框存在
    expect(screen.getByPlaceholderText('搜索订单ID或任务ID...')).toBeInTheDocument();

    // 验证刷新按钮存在
    expect(screen.getByText('刷新')).toBeInTheDocument();

    // 验证状态筛选器存在
    expect(screen.getAllByText('全部状态').length).toBeGreaterThan(0);
  });

  it('应该处理API错误', async () => {
    mockClient.getPrintTasks.mockRejectedValue(new Error('获取打印任务列表失败'));

    renderWithProviders(
      <PrintTaskQuery
        baseURL="/api/v1/feie"
        tenantId={123}
        authToken="test-token"
      />
    );

    // 应该显示错误UI
    await waitFor(() => {
      expect(screen.getByText('加载打印任务列表失败')).toBeInTheDocument();
    });

    // 验证重试按钮存在
    expect(screen.getByText('重试')).toBeInTheDocument();
  });

  it('应该支持多租户场景', async () => {
    const mockTasksData = {
      data: [],
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
        totalPages: 0,
      },
    };

    mockClient.getPrintTasks.mockResolvedValue(mockTasksData);

    renderWithProviders(
      <PrintTaskQuery
        baseURL="/api/v1/feie"
        tenantId={456}
        authToken="test-token"
      />
    );

    await waitFor(() => {
      expect(mockClient.getPrintTasks).toHaveBeenCalled();
    });

    // 验证租户ID设置
    expect(mockClient.setTenantId).toHaveBeenCalledWith(456);
    expect(mockClient.setAuthToken).toHaveBeenCalledWith('test-token');
  });

  it('应该显示空状态', async () => {
    const mockTasksData = {
      data: [],
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
        totalPages: 0,
      },
    };

    mockClient.getPrintTasks.mockResolvedValue(mockTasksData);

    renderWithProviders(
      <PrintTaskQuery
        baseURL="/api/v1/feie"
        tenantId={123}
        authToken="test-token"
      />
    );

    // 等待数据加载完成
    await waitFor(() => {
      expect(mockClient.getPrintTasks).toHaveBeenCalled();
    }, { timeout: 5000 });

    // 等待加载状态消失
    await waitFor(() => {
      const loadingElements = screen.queryAllByText('加载中...');
      expect(loadingElements.length).toBe(0);
    }, { timeout: 5000 });

    // 验证空状态显示 - 使用更灵活的选择器
    const emptyStateTexts = screen.getAllByText(/暂无打印任务|还没有打印任务记录/i);
    expect(emptyStateTexts.length).toBeGreaterThan(0);
  });
});