import { usePageData } from '@/lib/page/usePageData';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_SERVICE_TOKEN, LEAGUE_MEMBERSHIP_SERVICE_TOKEN } from '@/lib/di/tokens';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
import { LeagueAdminScheduleViewModel } from '@/lib/view-models/LeagueAdminScheduleViewModel';
import { LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
import { LeagueSeasonSummaryViewModel } from '@/lib/view-models/LeagueSeasonSummaryViewModel';
import type { RaceDTO } from '@/lib/types/generated/RaceDTO';
import type { LeagueSeasonSummaryDTO } from '@/lib/types/generated/LeagueSeasonSummaryDTO';
import { DateDisplay } from '@/lib/display-objects/DateDisplay';

function mapRaceDtoToViewModel(race: RaceDTO): LeagueScheduleRaceViewModel {
  const scheduledAt = race.date ? new Date(race.date) : new Date(0);
  const now = new Date();
  const isPast = scheduledAt.getTime() < now.getTime();

  return {
    id: race.id,
    name: race.name,
    scheduledAt,
    formattedDate: DateDisplay.formatShort(scheduledAt),
    formattedTime: DateDisplay.formatTime(scheduledAt),
    isPast,
    isUpcoming: !isPast,
    status: isPast ? 'completed' : 'scheduled',
    track: undefined,
    car: undefined,
    sessionType: undefined,
    isRegistered: undefined,
  };
}

export function useLeagueAdminStatus(leagueId: string, currentDriverId: string) {
  const leagueMembershipService = useInject(LEAGUE_MEMBERSHIP_SERVICE_TOKEN);

  return usePageData({
    queryKey: ['admin-check', leagueId, currentDriverId],
    queryFn: async () => {
      await leagueMembershipService.fetchLeagueMemberships(leagueId);
      const membership = leagueMembershipService.getMembership(leagueId, currentDriverId);
      return membership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role) : false;
    },
    enabled: !!leagueId && !!currentDriverId,
  });
}

export function useLeagueSeasons(leagueId: string, isAdmin: boolean) {
  const leagueService = useInject(LEAGUE_SERVICE_TOKEN);

  return usePageData({
    queryKey: ['leagueSeasons', leagueId],
    queryFn: async (): Promise<LeagueSeasonSummaryViewModel[]> => {
      const result = await leagueService.getLeagueSeasonSummaries(leagueId);
      if (result.isErr()) {
        throw new Error(result.getError().message);
      }
      const dtos = result.unwrap();
      return dtos.map((dto: LeagueSeasonSummaryDTO) => new LeagueSeasonSummaryViewModel(dto));
    },
    enabled: !!leagueId && !!isAdmin,
  });
}

export function useLeagueAdminSchedule(leagueId: string, selectedSeasonId: string, isAdmin: boolean) {
  const leagueService = useInject(LEAGUE_SERVICE_TOKEN);

  return usePageData({
    queryKey: ['adminSchedule', leagueId, selectedSeasonId],
    queryFn: async (): Promise<LeagueAdminScheduleViewModel> => {
      const result = await leagueService.getAdminSchedule(leagueId, selectedSeasonId);
      if (result.isErr()) {
        throw new Error(result.getError().message);
      }
      const dto = result.unwrap();
      const races = dto.races.map(mapRaceDtoToViewModel);
      return new LeagueAdminScheduleViewModel({
        seasonId: dto.seasonId,
        published: dto.published,
        races,
      });
    },
    enabled: !!leagueId && !!selectedSeasonId && !!isAdmin,
  });
}
