//
//  SeedsCallingView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 16/04/2024.
//

import SwiftUI
import LeStorage

struct SeedsCallingView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    @State private var displayByMatch: Bool = true
    
    var body: some View {
        List {
            if tournament.isPrivate {
                Section {
                    RowButtonView("Rendre visible sur Padel Club") {
                        tournament.isPrivate = false
                        do {
                            try dataStore.tournaments.addOrUpdate(instance: tournament)
                        } catch {
                            Logger.error(error)
                        }
                    }
                } footer: {
                    Text("Si vous convoquez un tournoi privée, les joueurs n'auront pas le lien pour suivre le tournoi.")
                        .foregroundStyle(.logoRed)
                }
            }

            let tournamentRounds = tournament.rounds()
            let uncalledSeeds = tournament.seededTeams().filter({ $0.callDate == nil })
            
            if uncalledSeeds.isEmpty == false {
                NavigationLink {
                    TeamsCallingView(teams: uncalledSeeds)
                        .environment(tournament)
                } label: {
                    LabeledContent("Équipe\(uncalledSeeds.count.pluralSuffix) non contactée\(uncalledSeeds.count.pluralSuffix)", value: uncalledSeeds.count.formatted())
                }
            }

            PlayersWithoutContactView(players: tournament.seededTeams().flatMap({ $0.unsortedPlayers() }).sorted(by: \.computedRank))

            ForEach(tournamentRounds) { round in
                let seeds = round.teamsOrSeeds()
                let callSeeds = seeds.filter({ tournament.isStartDateIsDifferentThanCallDate($0) == false })
                if seeds.isEmpty == false {
                    Section {
                        NavigationLink {
                            _roundView(round: round)
                                .environment(tournament)
                        } label: {
                            CallView.CallStatusView(count: callSeeds.count, total: seeds.count, startDate: round.playedMatches().first?.startDate)
                        }
                    } header: {
                        Text(round.roundTitle())
                    } footer: {
                        if let startDate = round.startDate ?? round.playedMatches().first?.startDate {
                            CallView(teams: seeds, callDate: startDate, matchFormat: round.matchFormat, roundLabel: round.roundTitle())
                        }
                    }
                }
            }
        }
        .headerProminence(.increased)
    }
    
    @ViewBuilder
    private func _roundView(round: Round) -> some View {
        let roundMatches = round.playedMatches()
        let times = Dictionary(grouping: roundMatches) { match in
            match.startDate
        }
        let keys = times.keys.compactMap { $0 }.sorted()
        List {
            
            Section {
                RowButtonView(displayByMatch ? "Regrouper par horaire" : "Lister par match") {
                    displayByMatch.toggle()
                }
            }
            
            let uncalledTeams = round.teams().filter({ $0.callDate == nil })
            if uncalledTeams.isEmpty == false {
                NavigationLink {
                    TeamsCallingView(teams: uncalledTeams)
                        .environment(tournament)
                } label: {
                    LabeledContent("Équipe\(uncalledTeams.count.pluralSuffix) non contactée\(uncalledTeams.count.pluralSuffix)", value: uncalledTeams.count.formatted())
                }
            }
            
            
            if displayByMatch == false {
                ForEach(keys, id: \.self) { time in
                    if let matches = times[time] {
                        let teams = matches.flatMap { round.seeds(inMatchIndex: $0.index) }
                        Section {
                            ForEach(teams) { team in
                                TeamRowView(team: team)
                            }
                        } header: {
                            HStack {
                                Text(time.localizedDate())
                                Spacer()
                                Text(teams.count.formatted() + " paire" + teams.count.pluralSuffix)
                            }
                        } footer: {
                            CallView(teams: teams, callDate: time, matchFormat: round.matchFormat, roundLabel: round.roundTitle())
                        }
                    }
                }
            } else {
                ForEach(roundMatches) { match in
                    let teams = round.seeds(inMatchIndex: match.index)
                    Section {
                        ForEach(teams) { team in
                            TeamCallView(team: team)
                        }
                    } header: {
                        HStack {
                            if let startDate = match.startDate {
                                Text(startDate.localizedDate())
                            } else {
                                Text("Aucun horaire")
                            }
                            Spacer()
                            Text(match.matchTitle())
                        }
                    } footer: {
                        if let startDate = match.startDate {
                            CallView(teams: teams, callDate: startDate, matchFormat: match.matchFormat, roundLabel: round.roundTitle())
                        }
                    }
                }
            }
        }
        .overlay {
            if (keys.isEmpty && displayByMatch == false) || (displayByMatch && roundMatches.isEmpty) {
                ContentUnavailableView {
                    Label("Aucun horaire défini", systemImage: "clock.badge.questionmark")
                } description: {
                    Text("Vous n'avez pas encore défini d'horaire pour les différentes phases du tournoi")
                } actions: {
//                    RowButtonView("Horaire intelligent") {
//                        selectedScheduleDestination = nil
//                    }
                }
            }
        }
        .headerProminence(.increased)
        .navigationTitle(round.roundTitle())
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}

//#Preview {
//    SeedsCallingView()
//}
