import { LeagueStandingsTemplate } from '@/templates/LeagueStandingsTemplate';
import { ServiceFactory } from '@/lib/services/ServiceFactory';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
import type { StandingEntryViewModel } from '@/lib/view-models/StandingEntryViewModel';

interface LeagueStandingsStaticProps {
  leagueId: string;
  currentDriverId?: string | null;
}

export default async function LeagueStandingsStatic({ leagueId, currentDriverId }: LeagueStandingsStaticProps) {
  const serviceFactory = new ServiceFactory(getWebsiteApiBaseUrl());
  const leagueService = serviceFactory.createLeagueService();
  
  let standings: StandingEntryViewModel[] = [];
  let drivers: DriverViewModel[] = [];
  let memberships: LeagueMembership[] = [];
  let loading = false;
  let error: string | null = null;
  let isAdmin = false;

  try {
    loading = true;
    const vm = await leagueService.getLeagueStandings(leagueId, currentDriverId || '');
    standings = vm.standings;
    drivers = vm.drivers.map((d) => new DriverViewModel({ ...d, avatarUrl: (d as any).avatarUrl ?? null }));
    memberships = vm.memberships;

    // Check if current user is admin
    const membership = vm.memberships.find(m => m.driverId === currentDriverId);
    isAdmin = membership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role) : false;
  } catch (err) {
    error = err instanceof Error ? err.message : 'Failed to load standings';
  } finally {
    loading = false;
  }

  if (loading) {
    return (
      <div className="text-center text-gray-400">
        Loading standings...
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-warning-amber">
        {error}
      </div>
    );
  }

  // Server components can't have event handlers, so we provide empty functions
  // The Interactive wrapper will add the actual handlers
  return (
    <LeagueStandingsTemplate
      standings={standings}
      drivers={drivers}
      memberships={memberships}
      leagueId={leagueId}
      currentDriverId={currentDriverId ?? null}
      isAdmin={isAdmin}
      onRemoveMember={() => {}}
      onUpdateRole={() => {}}
    />
  );
}