/* eslint-disable import-x/order */
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const { mockGetLeads, mockGetStats, mockCreate, mockUpdateStatus, mockDeleteLead } = vi.hoisted(() => ({
  mockGetLeads: vi.fn(),
  mockGetStats: vi.fn(),
  mockCreate: vi.fn(),
  mockUpdateStatus: vi.fn(),
  mockDeleteLead: vi.fn(),
}));

vi.mock('@/lib/leads-api', async () => {
  const actual = await vi.importActual('@/lib/leads-api');
  return {
    ...actual,
    leadsApi: {
      create: mockCreate,
      getLeads: mockGetLeads,
      getStats: mockGetStats,
      updateStatus: mockUpdateStatus,
      delete: mockDeleteLead,
    },
  };
});

import LeadsPage from '../page';

function createWrapper() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
    },
  });
  return function Wrapper({ children }: { children: React.ReactNode }) {
    return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
  };
}

const mockLeads = {
  data: [
    {
      id: '1',
      agentId: 'agent-1',
      name: 'Phạm Minh C',
      phone: '0903456789',
      email: 'pham.c@example.com',
      source: 'website',
      score: 85,
      notes: { text: 'Khách hàng VIP, quan tâm căn hộ cao cấp' },
      status: 'NEW' as const,
      createdAt: '2026-04-10T09:00:00Z',
      updatedAt: '2026-04-10T09:00:00Z',
    },
    {
      id: '2',
      agentId: 'agent-1',
      name: 'Lê Văn D',
      phone: '0904567890',
      email: null,
      source: 'referral',
      score: 60,
      notes: null,
      status: 'CONTACTED' as const,
      createdAt: '2026-04-08T15:00:00Z',
      updatedAt: '2026-04-09T10:00:00Z',
    },
  ],
  total: 2,
  page: 1,
  limit: 20,
  totalPages: 1,
};

const mockStatsData = {
  totalLeads: 10,
  byStatus: { NEW: 3, CONTACTED: 4, QUALIFIED: 2, CONVERTED: 1 },
  conversionRate: 10.0,
  avgScore: 72,
};

describe('LeadsPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockGetLeads.mockResolvedValue(mockLeads);
    mockGetStats.mockResolvedValue(mockStatsData);
  });

  it('renders the page title and add button', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });

    expect(screen.getByText('Quản lý lead')).toBeInTheDocument();
    expect(screen.getByText('Thêm lead')).toBeInTheDocument();
  });

  it('renders stats cards with data', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });

    await waitFor(() => {
      expect(screen.getByText('Tổng lead')).toBeInTheDocument();
      expect(screen.getByText('Tỷ lệ chuyển đổi')).toBeInTheDocument();
      expect(screen.getByText('Điểm TB')).toBeInTheDocument();
      expect(screen.getByText('Lead mới')).toBeInTheDocument();
    });

    await waitFor(() => {
      // Stats show the numbers
      expect(screen.getByText('10.0%')).toBeInTheDocument();
    });
  });

  it('renders lead data after loading', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });

    await waitFor(() => {
      // Names appear in both mobile card and desktop table views
      expect(screen.getAllByText('Phạm Minh C').length).toBeGreaterThan(0);
      expect(screen.getAllByText('Lê Văn D').length).toBeGreaterThan(0);
    });
  });

  it('shows empty state when no leads', async () => {
    mockGetLeads.mockResolvedValue({
      data: [],
      total: 0,
      page: 1,
      limit: 20,
      totalPages: 0,
    });

    render(<LeadsPage />, { wrapper: createWrapper() });

    await waitFor(() => {
      expect(screen.getByText('Chưa có lead nào')).toBeInTheDocument();
    });
  });

  it('opens create lead dialog', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });
    const user = userEvent.setup();

    await user.click(screen.getByText('Thêm lead'));

    await waitFor(() => {
      expect(screen.getByText('Thêm lead mới')).toBeInTheDocument();
      expect(screen.getByLabelText('Tên khách hàng *')).toBeInTheDocument();
      expect(screen.getByLabelText('Số điện thoại *')).toBeInTheDocument();
    });
  });

  it('renders the status filter', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });

    const select = screen.getByDisplayValue('Tất cả trạng thái');
    expect(select).toBeInTheDocument();
  });

  it('opens detail dialog when clicking a lead', async () => {
    render(<LeadsPage />, { wrapper: createWrapper() });
    const user = userEvent.setup();

    await waitFor(() => {
      expect(screen.getAllByText('Phạm Minh C').length).toBeGreaterThan(0);
    });

    // Click on a table row (tr elements have onClick handlers)
    const rows = document.querySelectorAll('tr[class*="cursor-pointer"]');
    if (rows[0]) {
      await user.click(rows[0] as HTMLElement);
    }

    await waitFor(() => {
      expect(screen.getByText('Chi tiết lead')).toBeInTheDocument();
    });
  });
});
