//
//  LoserRoundSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/06/2024.
//

import SwiftUI
import LeStorage

struct LoserRoundSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed
    @Environment(Tournament.self) var tournament: Tournament
    @State var upperBracketRound: UpperRound
    @State private var confirmationRequired: Bool = false
    @State private var presentConfirmation: Bool = false
    @State private var loserBracketMode: LoserBracketMode

    init(upperBracketRound: UpperRound) {
        self.upperBracketRound = upperBracketRound
        _loserBracketMode = .init(wrappedValue: upperBracketRound.round.loserBracketMode)
    }
    
    var body: some View {
        List {
            Section {
                RowButtonView(isEditingTournamentSeed.wrappedValue == true ? "Terminer l'édition" : "Éditer les tours joués") {
                    isEditingTournamentSeed.wrappedValue.toggle()
                }
            }
            
            Section {
                Picker(selection: $loserBracketMode) {
                    ForEach(LoserBracketMode.allCases) {
                        Text($0.localizedLoserBracketMode()).tag($0)
                    }
                } label: {
                    Text("Position des perdants")
                }
                .onChange(of: loserBracketMode) {
                    if upperBracketRound.round.allLoserRoundMatches().anySatisfy({ $0.hasEnded() }) == false {
                        _refreshLoserBracketMode()
                    } else {
                        confirmationRequired = true
                    }
                }
            } header: {
                Text("Matchs de classement")
            } footer: {
                if confirmationRequired == false {
                    Text(upperBracketRound.round.loserBracketMode.localizedLoserBracketModeDescription())
                } else {
                    _footerViewConfirmationRequired()
                        .onTapGesture(perform: {
                            presentConfirmation = true
                        })
                }
            }
            
            Section {
                RowButtonView("Synchroniser les noms des matchs") {
                    let allRoundMatches = upperBracketRound.loserRounds.flatMap({ $0.allMatches
                    })
                    allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) })
                    do {
                        try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allRoundMatches)
                    } catch {
                        Logger.error(error)
                    }
                }
            }
            
            Section {
                RowButtonView("Effacer les matchs de classements", role: .destructive) {
                    upperBracketRound.round.deleteLoserBracket()
                }
            }
            .disabled(upperBracketRound.round.loserRounds().isEmpty)

            Section {
                RowButtonView("Créer les matchs de classements", role: .destructive) {
                    await _addLoserBracketMatches()
                }
            }
            .disabled(upperBracketRound.round.loserRounds().isEmpty == false)
            
            //todo proposer ici l'impression des matchs de classements peut-être?
        }
        .confirmationDialog("Attention", isPresented: $presentConfirmation, actions: {
            Button("Confirmer", role: .destructive) {
                _refreshLoserBracketMode()
                confirmationRequired = false
            }
            
            Button("Annuler", role: .cancel) {
                loserBracketMode = upperBracketRound.round.loserBracketMode
            }

        })

    }
    
    private func _refreshLoserBracketMode() {
        let matches = upperBracketRound.round.loserRoundsAndChildren().flatMap({ $0._matches() })
        matches.forEach { match in
            match.resetTeamScores(outsideOf: [])
            match.resetMatch()
            if loserBracketMode == .automatic {
                match.updateTeamScores()
            }
            match.confirmed = false
        }

        upperBracketRound.round.loserBracketMode = 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(instance: upperBracketRound.round)
        } catch {
            Logger.error(error)
        }
    }
    
    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)
    }

    private func _addLoserBracketMatches() async {
        upperBracketRound.round.buildLoserBracket()
        upperBracketRound.round.disabledMatches().forEach { match in
            match._toggleLoserMatchDisableState(true)
        }
        do {
            try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: upperBracketRound.round.allLoserRoundMatches())
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    LoserRoundSettingsView()
//}
