//
//  RoundSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 31/03/2024.
//

import SwiftUI
import LeStorage

struct RoundSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed
    @Environment(Tournament.self) var tournament: Tournament

    var body: some View {
        List {
            if tournament.shouldVerifyBracket {
                Section {
                    RowButtonView("Valider l'état du tableau", role: .destructive) {
                        tournament.shouldVerifyBracket = false
                        do {
                            try dataStore.tournaments.addOrUpdate(instance: tournament)
                        } catch {
                            Logger.error(error)
                        }
                    }
                } footer: {
                    Text("Suite à un changement dans votre liste d'inscrits, veuillez vérifier l'intégrité de votre tableau et valider que tout est ok.")
                }
            }
            
//            Section {
//                RowButtonView("Enabled", role: .destructive) {
//                    let allMatches = tournament._allMatchesIncludingDisabled()
//                    allMatches.forEach({ 
//                        $0.disabled = false
//                        $0.byeState = false
//                    })
//                    try? dataStore.matches.addOrUpdate(contentOfs: allMatches)
//                }
//            }
            Section {
                RowButtonView("Retirer toutes les têtes de séries", role: .destructive) {
                    await _removeAllSeeds()
                }
            }
            
            Section {
                let roundIndex = tournament.rounds().count
                RowButtonView("Ajouter " + RoundRule.roundName(fromRoundIndex: roundIndex)) {
                    let round = Round(tournament: tournament.id, index: roundIndex, matchFormat: tournament.matchFormat)
                    let matchCount = RoundRule.numberOfMatches(forRoundIndex: roundIndex)
                    let matchStartIndex = RoundRule.matchIndex(fromRoundIndex: roundIndex)
                    let nextRound = round.nextRound()
                    var currentIndex = 0
                    let matches = (0..<matchCount).map { index in //0 is final match
                        let match = Match(round: round.id, index: index + matchStartIndex, matchFormat: round.matchFormat)
                        
                        if let nextRound, let followingMatch = match.getFollowingMatch(fromNextRoundId: nextRound.id) {
                            if followingMatch.disabled {
                                match.disabled = true
                            } else if index%2 == 1 && followingMatch.team(.one) != nil {
                                //index du match courant impair = position haut du prochain match
                                match.disabled = true
                            } else if index%2 == 0 && followingMatch.team(.two) != nil {
                                //index du match courant pair = position basse du prochain match
                                match.disabled = true
                            } else {
                                match.name = Match.setServerTitle(upperRound: round, matchIndex: currentIndex)
                                currentIndex += 1
                            }
                        } else {
                            match.name = Match.setServerTitle(upperRound: round, matchIndex: currentIndex)
                            currentIndex += 1
                        }
                        
                        return match
                    }
                    do {
                        try dataStore.rounds.addOrUpdate(instance: round)
                    } catch {
                        Logger.error(error)
                    }
                    do {
                        try dataStore.matches.addOrUpdate(contentOfs: matches)
                    } catch {
                        Logger.error(error)
                    }
                    round.buildLoserBracket()
                    matches.filter { $0.disabled }.forEach {                             $0._toggleLoserMatchDisableState(true)
                    }
                }
            }
            
            Section {
                if let lastRound = tournament.rounds().first { // first is final, last round
                    RowButtonView("Supprimer " + lastRound.roundTitle(), role: .destructive) {
                        do {
                            try dataStore.rounds.delete(instance: lastRound)
                        } catch {
                            Logger.error(error)
                        }
                    }
                }
            }
        }
    }
    
    private func _removeAllSeeds() async {
        tournament.unsortedTeams().forEach({ team in
            team.bracketPosition = nil
        })
        let ts = tournament.allRoundMatches().flatMap { match in
            match.teamScores
        }
        
        do {
            try DataStore.shared.teamScores.delete(contentOfs: ts)
        } catch {
            Logger.error(error)
        }
        do {
            try dataStore.teamRegistrations.addOrUpdate(contentOfs: tournament.unsortedTeams())
        } catch {
            Logger.error(error)
        }
        tournament.allRounds().forEach({ round in
            round.enableRound()
        })
        self.isEditingTournamentSeed.wrappedValue = true
    }
}

//#Preview {
//    RoundSettingsView()
//        .environment(Tournament.mock())
//        .environmentObject(DataStore.shared)
//}
