//
//  LoserRoundView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 04/04/2024.
//

import SwiftUI
import LeStorage

struct LoserRoundView: View {
    @Environment(Tournament.self) var tournament: Tournament
    @Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed
    
    let loserBracket: LoserRound
    
    private func _roundDisabled() -> Bool {
#if _DEBUG_TIME //DEBUGING TIME
        let start = Date()
        defer {
            let duration = Duration.milliseconds(Date().timeIntervalSince(start) * 1_000)
            print("func _roundDisabled", duration.formatted(.units(allowed: [.seconds, .milliseconds])))
        }
#endif
        return loserBracket.allMatches.allSatisfy({ $0.disabled == true })
    }
    
    private func _matches(loserRoundId: String?) -> [Match] {
        return loserBracket.allMatches.filter { $0.round == loserRoundId && (isEditingTournamentSeed.wrappedValue == true || (isEditingTournamentSeed.wrappedValue == false && $0.disabled == false)) }.sorted(by: \.index)
    }
    
    var body: some View {
        List {
            if isEditingTournamentSeed.wrappedValue == true {
                _editingView()
            }
            
            ForEach(loserBracket.rounds) { loserRound in
                let matches = _matches(loserRoundId: loserRound.id)
                if matches.isEmpty == false {
                    Section {
                        ForEach(matches) { match in
                            MatchRowView(match: match, matchViewStyle: .sectionedStandardStyle)
                                .overlay {
                                    if match.disabled && isEditingTournamentSeed.wrappedValue == true {
                                        Image(systemName: "xmark")
                                            .resizable()
                                            .scaledToFit()
                                            .opacity(0.6)
                                    }
                                }
                                .disabled(match.disabled)
                            
                            if isEditingTournamentSeed.wrappedValue == true {
                                RowButtonView(match.disabled ? "Jouer ce match" : "Ne pas jouer ce match", role: .destructive) {
                                    match._toggleMatchDisableState(!match.disabled)
                                }
                            }
                        }
                    } header: {
                        HStack {
                            if let seedInterval = loserRound.seedInterval() {
                                Text(seedInterval.localizedLabel(.wide))
                                let seedIntervalPointRange = seedInterval.pointsRange(tournamentLevel: tournament.tournamentLevel, teamsCount: tournament.teamCount)
                                Spacer()
                                Text(seedIntervalPointRange)
                                    .font(.caption)
                            } else {
                                if let previousRound = loserRound.previousRound() {
                                    if let seedInterval = previousRound.seedInterval() {
                                        Text(seedInterval.localizedLabel())
                                    } else {
                                        Text("no previous round")
                                    }
                                } else if let parentRound = loserRound.parentRound {
                                    if let seedInterval = parentRound.seedInterval() {
                                        Text(seedInterval.localizedLabel())
                                    } else {
                                        Text("no parent round")
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /*
            let shouldDisplayLoserRounds : Bool = isEditingTournamentSeed.wrappedValue == true ? true : (allMatches.first(where: { $0.disabled == false }) != nil)
            
            if shouldDisplayLoserRounds {
            } else {
                Section {
                    ContentUnavailableView("Aucun match joué", systemImage: "tennisball", description: Text("Il n'y aucun match à jouer dans ce tour de match de classement."))
                }
            }
             */
        }
        .headerProminence(.increased)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(isEditingTournamentSeed.wrappedValue == true ? "Valider" : "Modifier") {
                    isEditingTournamentSeed.wrappedValue.toggle()
                    
                    if isEditingTournamentSeed.wrappedValue == false {
                        let allRoundMatches = loserBracket.allMatches
                        allRoundMatches.forEach({ $0.name = $0.roundTitle() })
                        do {
                            try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: allRoundMatches)
                        } catch {
                            Logger.error(error)
                        }
                    }
                }
            }
        }
    }
    
    private func _editingView() -> some View {
        if _roundDisabled() {
            RowButtonView("Jouer ce tour", role: .destructive) {
                loserBracket.rounds.forEach { round in
                    round.enableRound()
                }
            }
        } else {
            RowButtonView("Ne pas jouer ce tour", role: .destructive) {
                loserBracket.rounds.forEach { round in
                    round.disableRound()
                }
            }
        }
    }
}
