import { useMutation } from '@tanstack/react-query';
import { useServices } from '@/lib/services/ServiceProvider';
import { CreateLeagueInputDTO } from '@/lib/types/generated/CreateLeagueInputDTO';
import { CreateLeagueOutputDTO } from '@/lib/types/generated/CreateLeagueOutputDTO';

export interface LeagueWizardFormModel {
  leagueId?: string;
  basics?: {
    name?: string;
    description?: string;
    visibility?: string;
    gameId?: string;
  };
  structure?: {
    mode?: string;
    maxDrivers?: number;
    maxTeams?: number;
    driversPerTeam?: number;
    multiClassEnabled?: boolean;
  };
  championships?: {
    enableDriverChampionship?: boolean;
    enableTeamChampionship?: boolean;
    enableNationsChampionship?: boolean;
    enableTrophyChampionship?: boolean;
  };
  scoring?: {
    patternId?: string;
    customScoringEnabled?: boolean;
  };
  dropPolicy?: {
    strategy?: string;
    n?: number;
  };
  timings?: {
    practiceMinutes?: number;
    qualifyingMinutes?: number;
    sprintRaceMinutes?: number;
    mainRaceMinutes?: number;
    sessionCount?: number;
    roundsPlanned?: number;
    raceDayOfWeek?: number;
    raceTimeUtc?: string;
    weekdays?: string[];
    recurrenceStrategy?: string;
    timezoneId?: string;
    seasonStartDate?: string;
  };
  stewarding?: {
    decisionMode?: string;
    requiredVotes?: number;
    requireDefense?: boolean;
    defenseTimeLimit?: number;
    voteTimeLimit?: number;
    protestDeadlineHours?: number;
    stewardingClosesHours?: number;
    notifyAccusedOnProtest?: boolean;
    notifyOnVoteRequired?: boolean;
  };
  seasonName?: string;
}

export function useCreateLeagueWizard() {
  const { leagueService } = useServices();

  return useMutation({
    mutationFn: async (params: { form: LeagueWizardFormModel; ownerId: string }): Promise<CreateLeagueOutputDTO> => {
      // Convert form to CreateLeagueInputDTO
      const input: CreateLeagueInputDTO = {
        name: params.form.basics?.name?.trim() ?? '',
        description: params.form.basics?.description?.trim() ?? '',
        visibility: (params.form.basics?.visibility as 'public' | 'private') ?? 'public',
        ownerId: params.ownerId,
      };
      
      // Use the league service to create the league
      const result = await leagueService.createLeague(input);
      
      return result;
    },
  });
}