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

import { ModelOverrideDictDialog } from '@/components/auth/ModelOverrideDictDialog';
import { TooltipProvider } from '@/components/ui/tooltip';
import { fetchProcurementDictionaryEntries } from '@/services/modelOverrideService';
import type { ProcurementDictionaryEntry } from '@/types';

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

vi.mock('@/lib/supabase', () => ({
  isSupabaseConfigured: () => true,
}));

vi.mock('@/services/modelOverrideService', async () => {
  const actual = await vi.importActual<typeof import('@/services/modelOverrideService')>('@/services/modelOverrideService');
  return {
    ...actual,
    fetchProcurementDictionaryEntries: vi.fn(),
  };
});

function createEntry(index: number): ProcurementDictionaryEntry {
  const padded = String(index).padStart(2, '0');
  return {
    id: `entry-${padded}`,
    term: `术语${padded}`,
    term_type: 'parameter',
    product_context: `语境${padded}`,
    interpretation: `参数解读${padded}`,
    suggested_keyword: `搜索词${padded}`,
    evidence: '测试数据',
    source_batch_id: 'BATCH-001',
    source_material_id: null,
    source_llm_model: 'test-model',
    occurrence_count: index,
    note: null,
    created_by: 'user-1',
    created_at: '2026-04-27T03:00:00.000Z',
    updated_at: '2026-04-27T03:00:00.000Z',
  };
}

describe('ModelOverrideDictDialog', () => {
  const fetchEntriesMock = vi.mocked(fetchProcurementDictionaryEntries);

  beforeEach(() => {
    vi.clearAllMocks();
    fetchEntriesMock.mockResolvedValue(Array.from({ length: 25 }, (_, index) => createEntry(index + 1)));
  });

  it('paginates long dictionary lists and resets to the first page when searching', async () => {
    render(
      <TooltipProvider>
        <ModelOverrideDictDialog open onOpenChange={vi.fn()} />
      </TooltipProvider>,
    );

    await waitFor(() => expect(fetchEntriesMock).toHaveBeenCalled());

    expect(screen.getByText('术语01')).toBeInTheDocument();
    expect(screen.getByText('术语20')).toBeInTheDocument();
    expect(screen.queryByText('术语21')).not.toBeInTheDocument();
    expect(screen.getByText('1 / 2')).toBeInTheDocument();
    expect(screen.getByText((_, element) => element?.textContent === '每页20条，共 25 条')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: '下一页' }));

    expect(screen.queryByText('术语01')).not.toBeInTheDocument();
    expect(screen.getByText('术语21')).toBeInTheDocument();
    expect(screen.getByText('2 / 2')).toBeInTheDocument();

    fireEvent.change(screen.getByPlaceholderText('搜索术语 / 解读 / 搜索词'), { target: { value: '术语03' } });

    expect(screen.getByText('术语03')).toBeInTheDocument();
    expect(screen.queryByText('术语21')).not.toBeInTheDocument();
    expect(screen.getByText('1 / 1')).toBeInTheDocument();
    expect(screen.getByText((_, element) => element?.textContent === '每页20条，共 1 条')).toBeInTheDocument();
  });
});
