//
//  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 tournamentStore: TournamentStore? {
        return self.tournament.tournamentStore
    }
    
    var body: some View {
        List {
            if tournament.shouldVerifyBracket {
                Section {
                    let issues = tournament.bracketTeamPlacementIssue()
                    DisclosureGroup {
                        ForEach(issues.shouldBeInIt, id: \.self) { id in
                            if let team: TeamRegistration = self.tournamentStore?.teamRegistrations.findById(id) {
                                TeamRowView(team: team)
                            }
                        }
                    } label: {
                        LabeledContent {
                            Text(issues.shouldBeInIt.count.formatted())
                        } label: {
                            Text("Équipes à mettre dans le tableau")
                        }
                    }
                    DisclosureGroup {
                        ForEach(issues.shouldNotBeInIt, id: \.self) { id in
                            if let team = self.tournamentStore?.teamRegistrations.findById(id) {
                                Menu {
                                    Button("Retirer du tableau") {
                                        team.resetBracketPosition()
                                        self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
                                    }
                                } label: {
                                    TeamRowView(team: team)
                                }
                            }
                        }
                    } label: {
                        LabeledContent {
                            Text(issues.shouldNotBeInIt.count.formatted())
                        } label: {
                            Text("Équipes à retirer du tableau")
                        }
                    }

                    RowButtonView("Valider l'état du tableau", role: .destructive) {
                        tournament.shouldVerifyBracket = false
                        dataStore.tournaments.addOrUpdate(instance: tournament)
                    }
                } 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.")
                }
            }
             
            let previewAvailable = tournament.rounds().flatMap({ $0.seeds() }).count < tournament.seedsCount() && tournament.lastDrawnDate() != nil && tournament.seedSpotsLeft()
            Section {
                NavigationLink {
                    DrawLogsView()
                        .environment(tournament)
                } label: {
                    Text("Gestionnaire des tirages au sort")
                }

                if previewAvailable {

                    NavigationLink {
                        PreviewBracketPositionView(seeds: tournament.seeds(), drawLogs: tournament.drawLogs().filter({ $0.drawType == .seed }))
                    } label: {
                        Text("Aperçu du repositionnement")
                    }
                    RowButtonView("Replacer toutes les têtes de série", role: .destructive) {
                        await tournament.updateSeedsBracketPosition()
                    }
                }
            } footer: {
                if previewAvailable {
                    Text("Vous avez une ou plusieurs places libres dans votre tableau. Pour respecter le tirage au sort effectué, vous pouvez décaler les têtes de séries.")
                }
            }
            
//            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), role: .destructive) {
                    await _addNewRound(roundIndex)
                }
            }
            
            Section {
                if let lastRound = tournament.rounds().first { // first is final, last round
                    RowButtonView("Supprimer " + lastRound.roundTitle(), role: .destructive) {
                        await _removeRound(lastRound)
                    }
                }
            }
            
            Section {
                RowButtonView("Synchroniser les noms des matchs") {
                    let allRoundMatches = tournament.allLoserRoundMatches()
                    allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) })
                    do {
                        try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allRoundMatches)
                    } catch {
                        Logger.error(error)
                    }
                }
            } header: {
                Text("Matchs de classement")
            }
        }
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                ShareLink(item: roundsPaste(), preview: .init("Données du tableau"))
            }
        }
    }
    
    func roundsPaste() -> TournamentRoundShareContent {
        TournamentRoundShareContent(tournament: tournament)
    }

    
    private func _removeAllSeeds() async {
        await tournament.removeAllSeeds(saveTeamsAtTheEnd: true)
        self.isEditingTournamentSeed.wrappedValue = true
    }
    
    private func _addNewRound(_ roundIndex: Int) async {
        await tournament.addNewRound(roundIndex)
    }
    
    private func _removeRound(_ lastRound: Round) async {
        do {
            let teams = lastRound.seeds()
            teams.forEach { team in
                team.resetBracketPosition()
            }
            try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
            try tournamentStore?.rounds.delete(instance: lastRound)
        } catch {
            Logger.error(error)
        }
    }
}

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