/* eslint-disable import-x/order */
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

// Mock next-intl
vi.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
  useLocale: () => 'vi',
}));

vi.mock('@/i18n/navigation', () => ({
  Link: ({
    children,
    href,
    ...props
  }: {
    children: React.ReactNode;
    href: string;
    [key: string]: unknown;
  }) => (
    <a href={href} {...props}>
      {children}
    </a>
  ),
  useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}));

vi.mock('next/image', () => ({
  default: ({ src, alt, ...props }: { src: string; alt: string; [key: string]: unknown }) => (
    <img src={src} alt={alt} {...(props as React.ImgHTMLAttributes<HTMLImageElement>)} />
  ),
}));

vi.mock('next/dynamic', () => ({
  default: () => {
    const Stub = () => <div data-testid="dynamic-stub" />;
    Stub.displayName = 'DynamicStub';
    return Stub;
  },
}));

const { notFoundMock } = vi.hoisted(() => ({
  notFoundMock: vi.fn(() => {
    throw new Error('NEXT_NOT_FOUND');
  }),
}));

vi.mock('next/navigation', () => ({
  notFound: notFoundMock,
}));

vi.mock('@/lib/hooks/use-residential-projects-flag', () => ({
  useResidentialProjectsFlag: vi.fn(() => true),
  isResidentialProjectsEnabledServer: vi.fn(() => true),
}));

// Mock TanStack Query
const mockSearchData = {
  data: [
    {
      id: 'proj-1',
      slug: 'vinhomes-grand-park',
      name: 'Vinhomes Grand Park',
      status: 'UNDER_CONSTRUCTION' as const,
      developer: { id: 'dev-1', name: 'Vingroup', logoUrl: null, totalProjects: 10 },
      city: 'Hồ Chí Minh',
      district: 'Quận 9',
      address: '1 Nguyễn Xiển',
      latitude: 10.84,
      longitude: 106.84,
      thumbnailUrl: '/img/project1.jpg',
      totalArea: 271000,
      totalUnits: 10000,
      propertyTypes: ['APARTMENT' as const, 'VILLA' as const],
      minPrice: '2000000000',
      maxPrice: '5000000000',
      completionDate: '2024-12-01',
      createdAt: '2023-01-15',
    },
  ],
  total: 1,
  page: 1,
  limit: 12,
  totalPages: 1,
};

vi.mock('@/lib/hooks/use-du-an', () => ({
  useProjectsSearch: vi.fn(() => ({
    data: mockSearchData,
    isLoading: false,
    isError: false,
  })),
  useProjectDetail: vi.fn(() => ({
    data: null,
    isLoading: false,
  })),
  useProjectLinkedListings: vi.fn(() => ({
    data: null,
    isLoading: false,
  })),
}));

vi.mock('@tanstack/react-query', () => ({
  useQuery: vi.fn(),
  QueryClient: vi.fn(),
  QueryClientProvider: ({ children }: { children: React.ReactNode }) => children,
}));

import DuAnPage from '../page';

describe('DuAnPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders the page header', () => {
    render(<DuAnPage />);
    expect(screen.getByText('Dự án bất động sản')).toBeDefined();
  });

  it('renders project cards from search data', () => {
    render(<DuAnPage />);
    expect(screen.getByText('Vinhomes Grand Park')).toBeDefined();
    expect(screen.getByText('Quận 9, Hồ Chí Minh')).toBeDefined();
  });

  it('renders view mode toggle buttons', () => {
    render(<DuAnPage />);
    expect(screen.getByLabelText('Xem dạng lưới')).toBeDefined();
    expect(screen.getByLabelText('Xem dạng danh sách')).toBeDefined();
    expect(screen.getByLabelText('Xem trên bản đồ')).toBeDefined();
  });

  it('shows loading skeleton when isLoading', async () => {
    const { useProjectsSearch } = await import('@/lib/hooks/use-du-an');
    vi.mocked(useProjectsSearch).mockReturnValue({
      data: undefined,
      isLoading: true,
      isError: false,
    } as ReturnType<typeof useProjectsSearch>);

    const { container } = render(<DuAnPage />);
    const skeletons = container.querySelectorAll('.animate-pulse');
    expect(skeletons.length).toBeGreaterThan(0);
  });

  it('shows empty state when no results', async () => {
    const { useProjectsSearch } = await import('@/lib/hooks/use-du-an');
    vi.mocked(useProjectsSearch).mockReturnValue({
      data: { data: [], total: 0, page: 1, limit: 12, totalPages: 0 },
      isLoading: false,
      isError: false,
    } as unknown as ReturnType<typeof useProjectsSearch>);

    render(<DuAnPage />);
    expect(screen.getByText('Không tìm thấy dự án')).toBeDefined();
  });

  it('shows total results count', async () => {
    const { useProjectsSearch } = await import('@/lib/hooks/use-du-an');
    vi.mocked(useProjectsSearch).mockReturnValue({
      data: mockSearchData,
      isLoading: false,
      isError: false,
    } as ReturnType<typeof useProjectsSearch>);

    render(<DuAnPage />);
    expect(screen.getByText('1 dự án được tìm thấy')).toBeDefined();
  });

  it('calls notFound when residential_projects flag is disabled', async () => {
    const { useResidentialProjectsFlag } = await import(
      '@/lib/hooks/use-residential-projects-flag'
    );
    vi.mocked(useResidentialProjectsFlag).mockReturnValue(false);

    expect(() => render(<DuAnPage />)).toThrow('NEXT_NOT_FOUND');
    expect(notFoundMock).toHaveBeenCalled();
  });
});
