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

import SwiftUI

struct LoserRound: Identifiable, Selectable {
    let turnIndex: Int
    let rounds: [Round]
    
    var id: Int {
        return turnIndex
    }
    
    
    static func updateDestinations(fromLoserRounds loserRounds: [Round], inUpperBracketRound upperBracketRound: Round) -> [LoserRound] {
        var rounds = [LoserRound]()
        for (index, round) in loserRounds.enumerated() {
            rounds.append(LoserRound(turnIndex: index, rounds: upperBracketRound.loserRounds(forRoundIndex: round.index)))
        }
        
        return rounds
    }
    
    static func enabledLoserRounds(inLoserRounds loserRounds: [Round], inUpperBracketRound upperBracketRound: Round) -> [Round] {
        return loserRounds.filter { loserRound in
            upperBracketRound.loserRounds(forRoundIndex: loserRound.index).anySatisfy({ $0.isDisabled() == false })
        }
    }

    
}

extension LoserRound: Equatable {
    static func == (lhs: LoserRound, rhs: LoserRound) -> Bool {
        lhs.id == rhs.id
    }
    
    
    func selectionLabel() -> String {
        return "Tour #\(turnIndex + 1)"
    }
    
    func badgeValue() -> Int? {
        let playedMatches: [Match] = self.rounds.flatMap { $0.playedMatches() }
        let runningMatches: [Match] = playedMatches.filter { $0.isRunning() }
        return runningMatches.count
    }
    
    func badgeValueColor() -> Color? {
        return nil
    }
    
    func badgeImage() -> Badge? {
        return rounds.allSatisfy({ $0.hasEnded() }) ? .checkmark : nil
    }
}


struct LoserRoundsView: View {
    var upperBracketRound: Round
    @State private var selectedRound: LoserRound?
    let loserRounds: [Round]
    @State private var allDestinations: [LoserRound]
    
    init(upperBracketRound: Round) {
        self.upperBracketRound = upperBracketRound
        let _loserRounds = upperBracketRound.loserRounds()
        self.loserRounds = _loserRounds
        let rounds = LoserRound.updateDestinations(fromLoserRounds: _loserRounds, inUpperBracketRound: upperBracketRound)
        _allDestinations = State(wrappedValue: rounds)
        
        _selectedRound = State(wrappedValue: rounds.first(where: { $0.rounds.anySatisfy({ $0.getActiveLoserRound() != nil }) }) ?? rounds.first)
    }

    var body: some View {
        VStack(spacing: 0) {
            GenericDestinationPickerView(selectedDestination: $selectedRound, destinations: allDestinations, nilDestinationIsValid: false)
            LoserRoundView(loserRounds: selectedRound!.rounds)
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}
