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

import SearchResults from '@/pages/SearchResults';
import type { SearchResult, SearchStageSummary } from '@/types';

const mockBundle = vi.hoisted(() => ({
  data: {
    searchResults: [] as SearchResult[],
    stageSummaries: [] as SearchStageSummary[],
    merchantContacts: [],
    materials: [
      {
        id: 'material-1',
        material_name: '测试材料',
        specification: '',
        quantity: 1,
        unit: '个',
        technical_standard: '',
        material_requirement: '',
        technical_requirement: '',
        applicable_conditions: '',
        test_requirement: '',
        acceptance_note: '',
        warranty_period: '',
        deadline: '',
        invoice_type: '',
        brand: '',
        remarks: '',
        delivery_address: '',
        source_file: '',
        batch_id: 'CG-TEST-001',
        created_at: '2026-05-04T00:00:00.000Z',
      },
    ],
    standardized: [
      {
        id: 'standardized-1',
        batch_id: 'CG-TEST-001',
        material_id: 'material-1',
        invoice_type: '',
        original_name: '测试材料',
        original_spec: '',
        standardized_name: '标准测试材料',
        category: '',
        brand: '',
        notes: '',
        delivery_address: '',
        primary_search_term: '标准测试材料',
        alt_search_terms: [],
        standardized_spec: '',
        standardized_unit: '个',
        quantity: 1,
        product_type: '',
        llm_model: '',
        ai_reasoning: '',
        created_at: '2026-05-04T00:00:00.000Z',
      },
    ],
    contactLogs: [],
  },
}));

vi.mock('@/hooks/useRealtimeDataQueries', () => ({
  useSearchResultsBundleQuery: () => ({
    data: mockBundle.data,
    error: null,
    isLoading: false,
    refetch: vi.fn(async () => ({ data: mockBundle.data })),
  }),
}));

vi.mock('@/hooks/useProcurementBatchOptions', () => ({
  useProcurementBatchOptions: () => ({ batchOptions: [] }),
}));

vi.mock('@/services/searchService', () => ({
  deleteSearchResultsByIds: vi.fn(),
  deleteSearchStageGroup: vi.fn(),
}));

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

function createSearchResult(overrides: Partial<SearchResult>): SearchResult {
  return {
    id: 'result-1',
    task_id: 'task-1',
    batch_id: 'CG-TEST-001',
    keyword: '标准测试材料',
    material_id: 'material-1',
    material_name: '测试材料',
    standardized_name: '标准测试材料',
    result_index: 0,
    title: '测试商品',
    price: '',
    offer_url: 'https://example.test/offer',
    image_url: 'https://img.example.test/product.jpg',
    screenshot_path: '',
    screenshot_public_url: 'https://img.example.test/screenshot.png',
    merchant_name: '测试商家',
    merchant_url: '',
    contact_type: '',
    contact_url: '',
    contact_handle: '',
    contact_site: '',
    contact_page_url: '',
    contact_person: '',
    phone: '',
    mobile: '',
    address: '',
    image_error: '',
    created_at: '2026-05-04T00:00:00.000Z',
    score: 90,
    is_match: true,
    reason: '匹配',
    stage_order: 1,
    stage_label: '首轮搜索',
    stage_kind: 'keyword',
    stage_main_keyword: '标准测试材料',
    stage_keyword_hit_rate: 1,
    is_placeholder: false,
    placeholder_reason: '',
    ...overrides,
  };
}

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

  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter>
        <SearchResults />
      </MemoryRouter>
    </QueryClientProvider>,
  );
}

async function selectKeywordSection() {
  const keywordButton = await screen.findByRole('button', { name: /标准测试材料/ });
  fireEvent.click(keywordButton);
}

describe('SearchResults screenshot preview', () => {
  beforeEach(() => {
    mockBundle.data.searchResults = [
      createSearchResult({ id: 'result-1', title: '测试商品', result_index: 0 }),
      createSearchResult({
        id: 'placeholder-1',
        title: '占位商品',
        result_index: 1,
        image_url: '',
        screenshot_public_url: '',
        is_placeholder: true,
        placeholder_reason: 'no_candidates',
      }),
    ];
    mockBundle.data.stageSummaries = [];
  });

  it('previews and zooms non-placeholder screenshots without closing the product detail dialog', async () => {
    renderPage();
    await selectKeywordSection();

    const detailButtons = await screen.findAllByRole('button', { name: '详情' });
    fireEvent.click(detailButtons[0]);
    const detailDialog = screen.getByRole('dialog', { name: '测试商品' });
    fireEvent.click(within(detailDialog).getByRole('button', { name: '预览商品截图' }));

    const previewDialog = screen.getByRole('dialog', { name: '商品截图预览' });
    expect(within(previewDialog).getByRole('img', { name: '测试商品' })).toHaveAttribute('src', 'https://img.example.test/screenshot.png');
    expect(within(previewDialog).getByText('100%')).toBeInTheDocument();

    fireEvent.click(within(previewDialog).getByRole('button', { name: '放大' }));
    expect(within(previewDialog).getByText('125%')).toBeInTheDocument();

    fireEvent.click(within(previewDialog).getByRole('button', { name: '缩小' }));
    expect(within(previewDialog).getByText('100%')).toBeInTheDocument();

    fireEvent.click(within(previewDialog).getByRole('button', { name: 'Close' }));

    await waitFor(() => {
      expect(screen.queryByRole('dialog', { name: '商品截图预览' })).not.toBeInTheDocument();
    });
    expect(screen.getByRole('dialog', { name: '测试商品' })).toBeInTheDocument();
  });

  it('does not show screenshot preview controls for placeholder results', async () => {
    renderPage();
    await selectKeywordSection();

    fireEvent.click(screen.getByText('占位商品'));
    const detailDialog = screen.getByRole('dialog', { name: '占位商品' });

    expect(within(detailDialog).queryByRole('button', { name: '预览商品截图' })).not.toBeInTheDocument();
    expect(within(detailDialog).queryByText('点击预览')).not.toBeInTheDocument();
  });
});
