//
//  GroupStageQualificationManager.swift
//  PadelClub
//
//  Created by razmig on 05/11/2024.
//


class GroupStageQualificationManager {
    private let tournament: Tournament
    private let tournamentStore: TournamentStore

    init(tournament: Tournament, tournamentStore: TournamentStore) {
        self.tournament = tournament
        self.tournamentStore = tournamentStore
    }

    func qualificationSection() -> some View {
        guard tournament.groupStageAdditionalQualified > 0 else { return EmptyView() }

        let name = "\(tournament.qualifiedPerGroupStage + 1).ordinalFormatted()"
        let missingQualifiedFromGroupStages = tournament.missingQualifiedFromGroupStages()

        return Section {
            NavigationLink {
                SpinDrawView(
                    drawees: missingQualifiedFromGroupStages.isEmpty 
                        ? tournament.groupStageAdditionalQualifiedPreDraw() 
                        : ["Qualification d'un \(name) de poule"],
                    segments: missingQualifiedFromGroupStages.isEmpty 
                        ? tournament.groupStageAdditionalLeft() 
                        : missingQualifiedFromGroupStages
                ) { results in
                    if !missingQualifiedFromGroupStages.isEmpty {
                        self.handleDrawResults(results, missingQualifiedFromGroupStages)
                    }
                }
            } label: {
                Label {
                    Text("Qualifier un \(name) de poule par tirage au sort")
                } icon: {
                    Image(systemName: "exclamationmark.circle.fill")
                        .foregroundStyle(.logoBackground)
                }
            }
            .disabled(tournament.moreQualifiedToDraw() == 0)
        } footer: {
            footerText(missingQualifiedFromGroupStages.isEmpty)
        }
    }

    private func handleDrawResults(_ results: [DrawResult], _ missingQualifiedFromGroupStages: [Team]) {
        results.forEach { drawResult in
            var team = missingQualifiedFromGroupStages[drawResult.drawIndex]
            team.qualified = true
            do {
                try tournamentStore.teamRegistrations.addOrUpdate(instance: team)
            } catch {
                Logger.error(error)
            }
        }
    }

    private func footerText(_ noMoreTeams: Bool) -> Text {
        if tournament.moreQualifiedToDraw() == 0 {
            return Text("Aucune équipe supplémentaire à qualifier. Vous pouvez en rajouter en modifiant le paramètre dans structure.")
        } else if noMoreTeams {
            return Text("Aucune équipe supplémentaire à tirer au sort. Attendez la fin des poules.")
        }
        return Text("")
    }
}
