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

import SwiftUI

struct LoserRoundView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    
    let loserRounds: [Round]
    @State private var isEditingTournamentSeed: Bool = false

    private func _roundDisabled() -> Bool {
        loserRounds.allSatisfy({ $0.isDisabled() })
    }
    
    var body: some View {
        List {
            if isEditingTournamentSeed == true {
                _editingView()
            }
            
            ForEach(loserRounds) { loserRound in
                if true {
                    Section {
                        let matches = loserRound.playedMatches().sorted(by: \.index)
                        ForEach(matches) { match in
                            MatchRowView(match: match, matchViewStyle: .sectionedStandardStyle)
                                .overlay {
                                    if match.disabled /*&& isEditingTournamentSeed*/ {
                                        Image(systemName: "xmark")
                                            .resizable()
                                            .scaledToFit()
                                            .opacity(0.8)
                                    }
                                }
                                .disabled(match.disabled)
                        }
                    } header: {
                        HStack {
                            Text(loserRound.roundTitle(.wide))
                            let tournamentTeamCount = tournament.teamCount
                            if let seedIntervalPointRange = loserRound.seedInterval()?.pointsRange(tournamentLevel: tournament.tournamentLevel, teamsCount: tournamentTeamCount) {
                                Spacer()
                                Text(seedIntervalPointRange)
                                    .font(.caption)
                            }
                        }
                    }
                }
            }
        }
        .headerProminence(.increased)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(isEditingTournamentSeed == true ? "Valider" : "Modifier") {
                    isEditingTournamentSeed.toggle()
                }
            }
        }
    }
    
    private func _editingView() -> some View {
        if _roundDisabled() {
            RowButtonView("Jouer ce tour", role: .destructive) {
                loserRounds.forEach { round in
                    round.enableRound()
                }
            }
        } else {
            RowButtonView("Ne pas jouer ce tour", role: .destructive) {
                loserRounds.forEach { round in
                    round.disableRound()
                }
            }
        }
    }
}
