import { RacesTemplate } from '@/templates/RacesTemplate';
import { RaceService } from '@/lib/services/races/RaceService';
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';

export default async function Page() {
  // Create dependencies for API clients
  const baseUrl = getWebsiteApiBaseUrl();
  const logger = new ConsoleLogger();
  const errorReporter = new EnhancedErrorReporter(logger, {
    showUserNotifications: true,
    logToConsole: true,
    reportToExternal: process.env.NODE_ENV === 'production',
  });

  // Create API client
  const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);

  // Create service
  const service = new RaceService(racesApiClient);
  
  const data = await service.getRacesPageData();
  
  // Transform data for template
  const transformRace = (race: any) => ({
    id: race.id,
    track: race.track,
    car: race.car,
    scheduledAt: race.scheduledAt,
    status: race.status as 'scheduled' | 'running' | 'completed' | 'cancelled',
    sessionType: 'race',
    leagueId: race.leagueId,
    leagueName: race.leagueName,
    strengthOfField: race.strengthOfField ?? undefined,
    isUpcoming: race.isUpcoming,
    isLive: race.isLive,
    isPast: race.isPast,
  });

  const races = data.races.map(transformRace);
  const scheduledRaces = data.scheduledRaces.map(transformRace);
  const runningRaces = data.runningRaces.map(transformRace);
  const completedRaces = data.completedRaces.map(transformRace);
  const totalCount = data.totalCount;
  
  return <RacesTemplate
    races={races}
    totalCount={totalCount}
    scheduledRaces={scheduledRaces}
    runningRaces={runningRaces}
    completedRaces={completedRaces}
    isLoading={false}
    statusFilter="all"
    setStatusFilter={() => {}}
    leagueFilter="all"
    setLeagueFilter={() => {}}
    timeFilter="upcoming"
    setTimeFilter={() => {}}
    onRaceClick={() => {}}
    onLeagueClick={() => {}}
    onRegister={() => {}}
    onWithdraw={() => {}}
    onCancel={() => {}}
    showFilterModal={false}
    setShowFilterModal={() => {}}
    currentDriverId={undefined}
    userMemberships={[]}
  />;
}