//
//  PlanningByCourtView.swift
//  PadelClub
//
//  Created by razmig on 24/08/2024.
//

import SwiftUI

struct PlanningByCourtView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    
    let matches: [Match]
    @Binding var selectedScheduleDestination: ScheduleDestination?
    @State private var viewByCourt: Bool = false
    @State private var selectedDay: Date
    @State private var selectedCourt: Int = 0
    @State private var uuid: UUID = UUID()
    
    var timeSlots: [Date:[Match]] {
        Dictionary(grouping: matches.filter({ $0.startDate != nil })) { $0.startDate! }
    }
    
    var days: [Date] {
        Set(timeSlots.keys.map { $0.startOfDay }).sorted()
    }
    
    var keys: [Date] {
        timeSlots.keys.sorted()
    }
    
    var courts: [Int] {
        courtSlots.keys.sorted()
    }
    
    var courtSlots: [Int:[Match]] {
        Dictionary(grouping: matches) { $0.courtIndex ?? Int.max }
    }
    
    init(matches: [Match], selectedScheduleDestination: Binding<ScheduleDestination?>, startDate: Date) {
        self.matches = matches.filter({ $0.endDate == nil })
        _selectedScheduleDestination = selectedScheduleDestination
        _selectedDay = State(wrappedValue: startDate)
    }
    
    @ViewBuilder
    var body: some View {
        let noStartDate = matches.allSatisfy({ $0.startDate == nil })
        
        List {
            _byCourtView(selectedCourt: selectedCourt, selectedDay: selectedDay, noStartDate: noStartDate)
                .id(uuid)
        }
        .onChange(of: selectedCourt) {
            uuid = UUID()
        }
        .onChange(of: selectedDay) {
            uuid = UUID()
        }
        .overlay {
            if noStartDate {
                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
                    }
                }
            }
        }
        .navigationTitle(Text(selectedDay.formatted(.dateTime.day().weekday().month())))
        .toolbar {
            if days.count > 1 {
                ToolbarTitleMenu {
                    Picker(selection: $selectedDay) {
                        ForEach(days, id: \.self) { day in
                            Text(day.formatted(.dateTime.day().weekday().month())).tag(day as Date?)
                        }
                    } label: {
                        Text("Jour")
                    }
                    .pickerStyle(.automatic)
                }
            }
            ToolbarItemGroup(placement: .topBarTrailing) {
                if courts.count > 1 {
                    Picker(selection: $selectedCourt) {
                        ForEach(courts, id: \.self) { courtIndex in
                            if courtIndex == Int.max {
                                Label("Sans terrain", systemImage: "rectangle.slash").tag(Int.max)
                            } else {
                                Text(tournament.courtName(atIndex: courtIndex)).tag(courtIndex)
                            }
                        }
                    } label: {
                        Text("Terrain")
                    }
                    .pickerStyle(.automatic)
                }
            }
        }
    }
    
    @ViewBuilder
    func _byCourtView(selectedCourt: Int, selectedDay: Date, noStartDate: Bool) -> some View {
        if let _matches = courtSlots[selectedCourt]?.filter({ $0.startDate?.dayInt == selectedDay.dayInt })  {
            let _sortedMatches = _matches.sorted(by: \.computedStartDateForSorting)
            if _sortedMatches.isEmpty == false {
                ForEach(_sortedMatches.indices, id: \.self) { index in
                    let match = _sortedMatches[index]
                    Section {
                        MatchRowView(match: match)
                            .matchViewStyle(.feedStyle)
                    } header: {
                        if let startDate = match.startDate {
                            if index > 0 {
                                if match.confirmed {
                                    Text("Pas avant \(startDate.formatted(date: .omitted, time: .shortened))")
                                } else {
                                    Text("Suivi de")
                                }
                            } else {
                                Text("Démarrage à \(startDate.formatted(date: .omitted, time: .shortened))")
                            }
                        } else {
                            Text("Aucun horaire")
                        }
                    }
                    .headerProminence(.increased)
                }
            } else if noStartDate == false {
                ContentUnavailableView {
                    Label("Aucun match planifié", systemImage: "clock.badge.questionmark")
                } description: {
                    Text("Aucun match n'a été planifié sur ce terrain et au jour sélectionné")
                } actions: {
                }
            }
        } else if noStartDate == false {
            ContentUnavailableView {
                Label("Aucun match planifié", systemImage: "clock.badge.questionmark")
            } description: {
                Text("Aucun match n'a été planifié sur ce terrain et au jour sélectionné")
            } actions: {
            }
        }
    }    
}
