/* 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 { mockGetMyInquiries, mockMarkAsRead } = vi.hoisted(() => ({
  mockGetMyInquiries: vi.fn(),
  mockMarkAsRead: vi.fn(),
}));

vi.mock('@/lib/inquiries-api', () => ({
  inquiriesApi: {
    getMyInquiries: mockGetMyInquiries,
    getByListing: vi.fn(),
    markAsRead: mockMarkAsRead,
  },
}));

import InquiriesPage 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 mockInquiries = {
  data: [
    {
      id: '1',
      listingId: 'listing-1',
      listingTitle: 'Bán căn hộ 2PN Quận 7',
      userId: 'user-1',
      userName: 'Nguyễn Văn A',
      userPhone: '0901234567',
      message: 'Tôi muốn xem căn hộ này cuối tuần',
      phone: null,
      isRead: false,
      createdAt: '2026-04-10T10:00:00Z',
    },
    {
      id: '2',
      listingId: 'listing-2',
      listingTitle: 'Cho thuê nhà phố Quận 2',
      userId: 'user-2',
      userName: 'Trần Thị B',
      userPhone: '0912345678',
      message: 'Giá thuê có thương lượng được không?',
      phone: '0912345678',
      isRead: true,
      createdAt: '2026-04-09T14:30:00Z',
    },
  ],
  total: 2,
  page: 1,
  limit: 20,
  totalPages: 1,
};

describe('InquiriesPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockGetMyInquiries.mockResolvedValue(mockInquiries);
  });

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

    expect(screen.getByText('Quản lý liên hệ')).toBeInTheDocument();
    expect(
      screen.getByText('Xem và phản hồi các yêu cầu tư vấn từ khách hàng'),
    ).toBeInTheDocument();
  });

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

    await waitFor(() => {
      expect(screen.getByText('Tổng liên hệ')).toBeInTheDocument();
    });

    // Stats labels are inside CardDescription elements
    const statCards = screen.getAllByText('Tổng liên hệ');
    expect(statCards).toHaveLength(1);
  });

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

    await waitFor(() => {
      // Names should appear in both mobile and desktop views
      expect(screen.getAllByText('Nguyễn Văn A').length).toBeGreaterThan(0);
      expect(screen.getAllByText('Trần Thị B').length).toBeGreaterThan(0);
    });
  });

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

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

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

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

    const select = screen.getByDisplayValue('Tất cả');
    expect(select).toBeInTheDocument();
  });

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

    await waitFor(() => {
      expect(screen.getAllByText('Nguyễn Văn A').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 liên hệ')).toBeInTheDocument();
    });
  });
});
