import { PageWrapper } from '@/components/shared/state/PageWrapper';
import { LeagueStandingsTemplate } from '@/templates/LeagueStandingsTemplate';
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
import { LeagueService } from '@/lib/services/leagues/LeagueService';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
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';
import { notFound } from 'next/navigation';
import type { LeagueStandingsViewModel } from '@/lib/view-models/LeagueStandingsViewModel';
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
import type { LeagueMembership } from '@/lib/types/LeagueMembership';

interface Props {
  params: { id: string };
}

export default async function Page({ params }: Props) {
  // Validate params
  if (!params.id) {
    notFound();
  }

  // Fetch data using PageDataFetcher.fetchManual for multiple dependencies
  const data = await PageDataFetcher.fetchManual(async () => {
    // Create dependencies
    const baseUrl = getWebsiteApiBaseUrl();
    const logger = new ConsoleLogger();
    const errorReporter = new EnhancedErrorReporter(logger, {
      showUserNotifications: true,
      logToConsole: true,
      reportToExternal: process.env.NODE_ENV === 'production',
    });

    // Create API clients
    const leaguesApiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
    const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger);
    const sponsorsApiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
    const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);

    // Create service
    const service = new LeagueService(
      leaguesApiClient,
      driversApiClient,
      sponsorsApiClient,
      racesApiClient
    );

    // Fetch data - using empty string for currentDriverId since this is SSR without session
    const result = await service.getLeagueStandings(params.id, '');
    if (!result) {
      throw new Error('League standings not found');
    }
    return result;
  });

  if (!data) {
    notFound();
  }

  // Transform data for template
  const standings = data.standings ?? [];
  const drivers: DriverViewModel[] = data.drivers?.map((d) =>
    new DriverViewModel({
      id: d.id,
      name: d.name,
      avatarUrl: d.avatarUrl || null,
      iracingId: d.iracingId,
      rating: d.rating,
      country: d.country,
    })
  ) ?? [];
  const memberships: LeagueMembership[] = data.memberships ?? [];

  // Create a wrapper component that passes data to the template
  const TemplateWrapper = () => {
    return (
      <LeagueStandingsTemplate
        standings={standings}
        drivers={drivers}
        memberships={memberships}
        leagueId={params.id}
        currentDriverId={null}
        isAdmin={false}
        onRemoveMember={() => {}}
        onUpdateRole={() => {}}
        loading={false}
      />
    );
  };

  return (
    <PageWrapper
      data={data}
      Template={TemplateWrapper}
      loading={{ variant: 'skeleton', message: 'Loading standings...' }}
      errorConfig={{ variant: 'full-screen' }}
      empty={{
        title: 'Standings not found',
        description: 'The standings for this league are not available.',
      }}
    />
  );
}