//
//  UmpireStatisticView.swift
//  PadelClub
//
//  Created by razmig on 06/11/2024.
//

import SwiftUI
import LeStorage

struct UmpireStatisticView: View {
    @EnvironmentObject var dataStore: DataStore

    let walkoutTeams: [TeamRegistration]
    let players: [PlayerRegistration]
    let countedPlayers: [String: Int]
    let countedWalkoutPlayers: [String: Int]
    
    init() {
        let teams = DataStore.shared.tournaments.filter { $0.isDeleted == false }.flatMap({ $0.unsortedTeams() })
        let wos = teams.filter({ $0.walkOut })
        self.walkoutTeams = wos
        
        var uniquePlayersDict = [String: PlayerRegistration]()
        var playerCountDict = [String: Int]()
        var playerWalkOutCountDict = [String: Int]()

        for team in teams {
            for player in team.unsortedPlayers() {
                if let licenceId = player.licenceId?.strippedLicense {
                    if team.walkOut {
                        uniquePlayersDict[licenceId] = player
                        playerWalkOutCountDict[licenceId, default: 0] += 1
                    }
                    playerCountDict[licenceId, default: 0] += 1
                }
            }
        }
        
        self.players = Array(uniquePlayersDict.values).sorted(by: { a, b in
            playerWalkOutCountDict[a.licenceId!.strippedLicense!]! > playerWalkOutCountDict[b.licenceId!.strippedLicense!]!
        })
        self.countedPlayers = playerCountDict
        self.countedWalkoutPlayers = playerWalkOutCountDict
    }
    
    var body: some View {
        List {
            Section {
                LabeledContent {
                    Text(dataStore.tournaments.count.formatted())
                } label: {
                    Text("Tournois")
                }
                
                LabeledContent {
                    Text(walkoutTeams.count.formatted())
                } label: {
                    Text("Équipes forfaites")
                }
            }
            
            if players.isEmpty == false {
                Section {
                    ForEach(players) { player in
                        LabeledContent {
                            if let licenceId = player.licenceId?.strippedLicense, let count = countedPlayers[licenceId], let walkoutCount = countedWalkoutPlayers[licenceId] {
                                Text(walkoutCount.formatted() + " / " + count.formatted())
                                    .font(.title3)
                            }
                        } label: {
                            Text(player.playerLabel())
                        }
                    }
                } header: {
                    Text("Nombre de forfaits / participations")
                }
            }
        }
        .navigationTitle("Statistiques")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}
