//
//  TournamentCategorySettingsView.swift
//  PadelClub
//
//  Created by razmig on 18/12/2024.
//


import SwiftUI
import LeStorage

struct TournamentCategorySettingsView: View {
    @Bindable var tournament: Tournament
    @EnvironmentObject var dataStore: DataStore
    @State private var confirmationRequired: Bool = false
    @State private var presentConfirmation: Bool = false
    @State private var loserBracketMode: LoserBracketMode

    init(tournament: Tournament) {
        self.tournament = tournament
        _loserBracketMode = .init(wrappedValue: tournament.loserBracketMode)
    }
    

    var body: some View {
        List {
            TournamentLevelPickerView()
            
            
            Section {
                Picker(selection: $loserBracketMode) {
                    ForEach(LoserBracketMode.allCases) {
                        Text($0.localizedLoserBracketMode()).tag($0)
                    }
                } label: {
                    Text("Position des perdants")
                }
                .onChange(of: loserBracketMode) {
                    if tournament.allLoserRoundMatches().anySatisfy({ $0.hasEnded() }) == false {
                        _refreshLoserBracketMode()
                    } else {
                        confirmationRequired = true
                    }
                }
            } header: {
                Text("Matchs de classement")
            } footer: {
                if confirmationRequired == false {
                    if dataStore.user.loserBracketMode != tournament.loserBracketMode {
                        _footerView()
                            .onTapGesture(perform: {
                                self.dataStore.user.loserBracketMode = tournament.loserBracketMode
                                self.dataStore.saveUser()
                            })
                    } else {
                        Text(tournament.loserBracketMode.localizedLoserBracketModeDescription())
                    }
                } else {
                    _footerViewConfirmationRequired()
                        .onTapGesture(perform: {
                            presentConfirmation = true
                        })
                }
            }

        }
        .confirmationDialog("Attention", isPresented: $presentConfirmation, actions: {
            Button("Confirmer", role: .destructive) {
                _refreshLoserBracketMode()
                confirmationRequired = false
            }
            Button("Annuler", role: .cancel) {
                loserBracketMode = tournament.loserBracketMode
            }
            
        })
        .toolbarBackground(.visible, for: .navigationBar)
        .onChange(of: [
            tournament.federalCategory,
        ]) {
            _save()
        }
        .onChange(of: [
            tournament.federalLevelCategory,
        ]) {
            tournament.setupFederalSettings()
            _save()
        }
        .onChange(of: [
            tournament.federalAgeCategory,
        ]) {
            _save()
        }
        .onChange(of: [
            tournament.groupStageSortMode,
        ]) {
            _save()
        }
    }
    
    private func _refreshLoserBracketMode() {
        tournament.loserBracketMode = loserBracketMode
        _save()
        
        let rounds = tournament.rounds()
        rounds.forEach { round in
            let matches = round.loserRoundsAndChildren().flatMap({ $0._matches() })
            matches.forEach { match in
                match.resetTeamScores(outsideOf: [])
                match.resetMatch()
                match.confirmed = false
            }

            round.loserBracketMode = tournament.loserBracketMode
            
            if loserBracketMode == .automatic {
                matches.forEach { match in
                    match.updateTeamScores()
                }
            }

            do {
                try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
            } catch {
                Logger.error(error)
            }
        }
        
        do {
            try self.tournament.tournamentStore?.rounds.addOrUpdate(contentOfs: rounds)
        } catch {
            Logger.error(error)
        }
    }

    
    private func _save() {
        do {
            if tournament.onlineRegistrationCanBeEnabled() == false, tournament.enableOnlineRegistration {
                tournament.enableOnlineRegistration = false
            }
            try dataStore.tournaments.addOrUpdate(instance: tournament)
        } catch {
            Logger.error(error)
        }
    }

    private func _footerView() -> some View {
        Text(tournament.loserBracketMode.localizedLoserBracketModeDescription())
        +
        Text(" Modifier le réglage par défaut pour tous vos tournois").foregroundStyle(.blue)
    }
    
    private func _footerViewConfirmationRequired() -> some View {
        Text("Au moins un match de classement est terminé, en modifiant ce réglage, les résultats de ces matchs de classement seront perdus.")
        +
        Text(" Modifier quand même ?").foregroundStyle(.red)
    }

}
