//
//  RoundsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 30/03/2024.
//

import SwiftUI

struct RoundsView: View {
    var tournament: Tournament
    @State private var selectedRound: UpperRound?
    @State private var isEditingTournamentSeed = false

    let destinations: [UpperRound]
    
    init(tournament: Tournament) {
        self.tournament = tournament
        let _destinations = tournament.rounds().map { UpperRound(round: $0) }
        self.destinations = _destinations
        let availableSeeds = tournament.availableSeeds()
        if tournament.shouldVerifyBracket {
            _selectedRound = State(wrappedValue: nil)
        } else {
            _selectedRound = State(wrappedValue: _destinations.first(where: { $0.id == tournament.getActiveRound()?.id }))
        }
        if availableSeeds.isEmpty == false || tournament.availableQualifiedTeams().isEmpty == false {
            _isEditingTournamentSeed = State(wrappedValue: true)
        }
    }
    
    var body: some View {
        VStack(spacing: 0) {
            GenericDestinationPickerView(selectedDestination: $selectedRound, destinations: destinations, nilDestinationIsValid: true)
            switch selectedRound {
            case .none:
                RoundSettingsView()
                    .navigationTitle("Réglages")
            case .some(let selectedRound):
                RoundView(upperRound: selectedRound).id(selectedRound.id)
                    .navigationTitle(selectedRound.round.roundTitle())
            }
        }
        .environment(\.isEditingTournamentSeed, $isEditingTournamentSeed)
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}

//#Preview {
//    RoundsView(tournament: Tournament.mock())
//}
