import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import SmartInquiry from '@/pages/SmartInquiry';
import { fetchInquiryBatchOptions, fetchInquiryTasks } from '@/services/inquiryService';
import { fetchInquiryStatuses } from '@/services/automationService';

vi.mock('react-router-dom', () => ({
  useSearchParams: () => [new URLSearchParams('tab=tasks')],
}));

vi.mock('@/services/inquiryService', () => ({
  fetchInquiryTasks: vi.fn(),
  fetchInquiryBatchOptions: vi.fn(),
}));

vi.mock('@/services/automationService', async () => {
  const actual = await vi.importActual<typeof import('@/services/automationService')>('@/services/automationService');
  return {
    ...actual,
    fetchInquiryStatuses: vi.fn(),
    stopInquiryBatch: vi.fn(),
    triggerInquiryBatch: vi.fn(),
    uploadInquiryImage: vi.fn(),
  };
});

vi.mock('@/services/accountService', () => ({
  fetchAccounts: vi.fn(() => Promise.resolve([])),
}));

vi.mock('@/hooks/useAuth', () => ({
  useAuth: () => ({ user: { id: 'user-1' } }),
}));

vi.mock('@/hooks/useProcurementBatchOptions', () => ({
  useProcurementBatchOptions: () => ({ batches: [{ batch_id: 'CG-TEST-001' }], batchOptions: [] }),
}));

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

function createTask(message: string) {
  return {
    id: 'chat-1',
    batch_id: 'CG-TEST-001',
    merchant_name: '测试商家',
    offer_url: 'https://example.test/offer',
    title: '测试商品',
    current_round: 1,
    status: 'WAITING_REPLY' as const,
    retry_count: 0,
    extracted_data: null,
    ask_context: {},
    chat_history: [
      {
        role: 'self' as const,
        content: message,
      },
    ],
    created_at: '2026-04-29T00:00:00.000Z',
    updated_at: '2026-04-29T00:00:00.000Z',
    last_interacted_at: '2026-04-29T00:00:00.000Z',
  };
}

describe('SmartInquiry', () => {
  const fetchInquiryTasksMock = vi.mocked(fetchInquiryTasks);
  const fetchInquiryBatchOptionsMock = vi.mocked(fetchInquiryBatchOptions);
  const fetchInquiryStatusesMock = vi.mocked(fetchInquiryStatuses);

  beforeEach(() => {
    fetchInquiryTasksMock.mockReset();
    fetchInquiryBatchOptionsMock.mockReset();
    fetchInquiryStatusesMock.mockReset();
    fetchInquiryBatchOptionsMock.mockResolvedValue([]);
    fetchInquiryStatusesMock.mockResolvedValue([]);
  });

  it('updates the open chat detail sheet when refreshed inquiry data changes', async () => {
    fetchInquiryTasksMock
      .mockResolvedValueOnce([createTask('第一轮消息')])
      .mockResolvedValueOnce([createTask('第二轮消息')]);

    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          retry: false,
          gcTime: 0,
        },
      },
    });

    render(
      <QueryClientProvider client={queryClient}>
        <SmartInquiry />
      </QueryClientProvider>,
    );

    await screen.findByText('测试商品');
    fireEvent.click(screen.getByText('测试商品'));

    await waitFor(() => {
      expect(within(screen.getByRole('dialog')).getByText('第一轮消息')).toBeInTheDocument();
    });

    await queryClient.invalidateQueries({ queryKey: ['inquiry', 'dashboard'] });

    await waitFor(() => {
      const dialog = screen.getByRole('dialog');
      expect(within(dialog).getByText('第二轮消息')).toBeInTheDocument();
      expect(within(dialog).queryByText('第一轮消息')).not.toBeInTheDocument();
    });
  });
});
