//
//  InscriptionInfoView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 27/03/2024.
//

import SwiftUI

struct InscriptionInfoView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament
    
    @State private var players : [PlayerRegistration] = []
    @State private var selectedTeams : [TeamRegistration] = []
    @State private var callDateIssue : [TeamRegistration] = []
    @State private var waitingList : [TeamRegistration] = []
    @State private var duplicates : [PlayerRegistration] = []
    @State private var problematicPlayers : [PlayerRegistration] = []
    @State private var inadequatePlayers : [PlayerRegistration] = []
    @State private var playersWithoutValidLicense : [PlayerRegistration] = []
    @State private var entriesFromBeachPadel : [TeamRegistration] = []
    @State private var playersMissing : [TeamRegistration] = []

    var body: some View {
        List {
            Section {
                let footerString = "via [beach-padel.app.fft.fr](\(URLs.beachPadel.rawValue))"

                LabeledContent {
                    Text(entriesFromBeachPadel.count.formatted())
                } label: {
                    Text("Paires importées")
                    Text(.init(footerString))
                }
                .listRowView(color: .indigo)
                
                LabeledContent {
                    Text(selectedTeams.filter { $0.called() }.count.formatted())
                } label: {
                    Text("Paires convoquées")
                    Text("Vous avez envoyé une convocation par sms ou email")
                }
                .listRowView(color: .cyan)

                LabeledContent {
                    Text(selectedTeams.filter { $0.confirmed() }.count.formatted())
                } label: {
                    Text("Paires ayant confirmées")
                    Text("Vous avez noté la confirmation de l'équipe")
                }
                .listRowView(color: .green)
            }

            Section {
                DisclosureGroup {
                    ForEach(callDateIssue) { team in
                        CallView.TeamView(team: team)
                        if let groupStage = team.groupStageObject(), let callDate = groupStage.startDate {
                            CallView(teams: [team], callDate: callDate, matchFormat: groupStage.matchFormat, roundLabel: "poule")
                        } else if let initialRound = team.initialRound(),
                                  let initialMatch = team.initialMatch(),
                                  let callDate = initialMatch.startDate {
                            CallView(teams: [team], callDate: callDate, matchFormat: initialMatch.matchFormat, roundLabel: initialRound.roundTitle())
                        }
                    }
                } label: {
                    LabeledContent {
                        Text(callDateIssue.count.formatted())
                    } label: {
                        Text("Erreur de convocation")
                    }
                }
                .listRowView(color: .brown)
            } footer: {
                Text("L'horaire de la convocation est différente du match initial")
            }
            
            let waitingListInBracket = waitingList.filter({ $0.bracketPosition != nil })
            let waitingListInGroupStage = waitingList.filter({ $0.groupStage != nil })

            Section {
                DisclosureGroup {
                    ForEach(waitingListInBracket) { team in
                        TeamDetailView(team: team)
                    }
                } label: {
                    LabeledContent {
                        Text(waitingListInBracket.count.formatted())
                    } label: {
                        Text("Dans le tableau")
                    }
                }
                .listRowView(color: .red)
                
                DisclosureGroup {
                    ForEach(waitingListInGroupStage) { team in
                        TeamDetailView(team: team)
                    }
                } label: {
                    LabeledContent {
                        Text(waitingListInGroupStage.count.formatted())
                    } label: {
                        Text("En poule")
                    }
                }
                .listRowView(color: .red)
            } header: {
                Text("Équipes non sélectionnées")
            } footer: {
                Text("Il s'agit des équipes déjà placé en poule ou tableau qui sont actuellement en attente à cause de l'arrivée d'une nouvelle équipe ou une modification de classement.")
            }
            
            Section {
                DisclosureGroup {
                    ForEach(duplicates) { player in
                        ImportedPlayerView(player: player)
                    }
                } label: {
                    LabeledContent {
                        Text(duplicates.count.formatted())
                    } label: {
                        Text("Doublons")
                    }
                }
                .listRowView(color: .red)
            }
            
            Section {
                DisclosureGroup {
                    ForEach(problematicPlayers) { player in
                        PlayerSexPickerView(player: player)
                    }
                } label: {
                    LabeledContent {
                        Text(problematicPlayers.count.formatted())
                    } label: {
                        Text("Joueurs problématiques")
                    }
                }
                .listRowView(color: .purple)
            } footer: {
                Text("Il s'agit des joueurs ou joueuses dont le sexe n'a pas pu être déterminé")
            }
            
            Section {
                DisclosureGroup {
                    ForEach(inadequatePlayers) { player in
                        ImportedPlayerView(player: player)
                    }
                } label: {
                    LabeledContent {
                        Text(inadequatePlayers.count.formatted())
                    } label: {
                        Text("Joueurs trop bien classés")
                    }
                }
                .listRowView(color: .red)
            } footer: {
                Text("Il s'agit des joueurs ou joueuses dont le rang est inférieur à la limite fédérale.")
            }
            
            Section {
                DisclosureGroup {
                    ForEach(playersWithoutValidLicense) {
                        EditablePlayerView(player: $0, editingOptions: [.licenceId])
                    }
                } label: {
                    LabeledContent {
                        Text(playersWithoutValidLicense.count.formatted())
                    } label: {
                        Text("Joueurs sans licence valide")
                    }
                }
                .listRowView(color: .orange)
            } footer: {
                Text("importé du fichier beach-padel sans licence valide ou créé sans licence")
            }
            
            Section {
                DisclosureGroup {
                    ForEach(playersMissing) {
                        TeamDetailView(team: $0)
                    }
                } label: {
                    LabeledContent {
                        Text(playersMissing.count.formatted())
                    } label: {
                        Text("Paires incomplètes")
                    }
                }
                .listRowView(color: .pink)
            }
        }
        .task {
            await _getIssues()
        }
        .navigationTitle("Synthèse")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
    
    private func _getIssues() async {
        Task {
            players = tournament.unsortedPlayers()
            selectedTeams = tournament.selectedSortedTeams()
            callDateIssue = selectedTeams.filter { $0.callDate != nil && tournament.isStartDateIsDifferentThanCallDate($0) }
            waitingList = tournament.waitingListTeams(in: selectedTeams)
            duplicates = tournament.duplicates(in: players)
            problematicPlayers = players.filter({ $0.sex == nil })
            inadequatePlayers = tournament.inadequatePlayers(in: players)
            playersWithoutValidLicense = tournament.playersWithoutValidLicense(in: players)
            entriesFromBeachPadel = tournament.unsortedTeams().filter({ $0.isImported() })
            playersMissing = selectedTeams.filter({ $0.unsortedPlayers().count < 2 })
        }
    }
}

//#Preview {
//    InscriptionInfoView()
//        .environment(Tournament.mock())
//}
