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

import SwiftUI

struct SeedsCallingView: View {
    @Environment(Tournament.self) var tournament: Tournament
    @State private var displayByMatch: Bool = false
    
    var body: some View {
        List {
            ForEach(tournament.rounds()) { round in
                let seeds = round.seeds()
                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 {
            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
                            CallView.TeamView(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)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(displayByMatch ? "par horaire" : "par match") {
                    displayByMatch.toggle()
                }
                .buttonBorderShape(.capsule)
            }
        }
    }
}

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