import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';

import LeagueSchedule from './LeagueSchedule';
import { LeagueScheduleViewModel } from '@/lib/view-models/LeagueScheduleViewModel';

const mockPush = vi.fn();

vi.mock('next/navigation', () => ({
  useRouter: () => ({
    push: mockPush,
  }),
}));

vi.mock('@/hooks/useEffectiveDriverId', () => ({
  useEffectiveDriverId: () => 'driver-123',
}));

const mockUseLeagueSchedule = vi.fn();
vi.mock('@/hooks/useLeagueService', () => ({
  useLeagueSchedule: (...args: unknown[]) => mockUseLeagueSchedule(...args),
}));

vi.mock('@/hooks/useRaceService', () => ({
  useRegisterForRace: () => ({
    mutateAsync: vi.fn(),
    isPending: false,
  }),
  useWithdrawFromRace: () => ({
    mutateAsync: vi.fn(),
    isPending: false,
  }),
}));

describe('LeagueSchedule', () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2025-01-01T00:00:00Z'));
    mockPush.mockReset();
    mockUseLeagueSchedule.mockReset();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('renders a schedule race (no crash)', () => {
    mockUseLeagueSchedule.mockReturnValue({
      isLoading: false,
      data: new LeagueScheduleViewModel([
        {
          id: 'race-1',
          name: 'Round 1',
          scheduledAt: new Date('2025-01-02T20:00:00Z'),
          isPast: false,
          isUpcoming: true,
          status: 'scheduled',
        },
      ]),
    });

    render(<LeagueSchedule leagueId="league-1" />);

    expect(screen.getByText('Round 1')).toBeInTheDocument();
  });

  it('renders loading state while schedule is loading', () => {
    mockUseLeagueSchedule.mockReturnValue({
      isLoading: true,
      data: undefined,
    });

    render(<LeagueSchedule leagueId="league-1" />);

    expect(screen.getByText('Loading schedule...')).toBeInTheDocument();
  });
});