//
//  EventListView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 29/02/2024.
//

import SwiftUI
import LeStorage

struct EventListView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(NavigationViewModel.self) var navigation: NavigationViewModel
    @Environment(FederalDataViewModel.self) var federalDataViewModel: FederalDataViewModel

    let tournaments: [FederalTournamentHolder]
    let viewStyle: AgendaDestination.ViewStyle
    let sortAscending: Bool

    var body: some View {
        let groupedTournamentsByDate = Dictionary(grouping: navigation.agendaDestination == .tenup ? federalDataViewModel.filteredFederalTournaments : tournaments) { $0.startDate.startOfMonth }
        switch viewStyle {
        case .list:
            ForEach(groupedTournamentsByDate.keys.sorted(by: sortAscending ? { $0 < $1 } : { $0 > $1 }), id: \.self) { section in
                if let _tournaments = groupedTournamentsByDate[section]?.sorted(by: sortAscending ? { $0.startDate < $1.startDate } : { $0.startDate > $1.startDate }
                ) {
                    Section {
                        _listView(_tournaments)
                    } header: {
                        HStack {
                            Text(section.monthYearFormatted)
                            Spacer()
                            let count = _tournaments.map { $0.tournaments.count }.reduce(0,+)
                            Text("\(count.formatted()) tournoi" + count.pluralSuffix)
                        }
                    }
                    .headerProminence(.increased)
                }
            }
        case .calendar:
            ForEach(_nextMonths(), id: \.self) { section in
                let _tournaments = groupedTournamentsByDate[section] ?? []
                Section {
                    CalendarView(date: section, tournaments: _tournaments).id(federalDataViewModel.id)
                } header: {
                    HStack {
                        Text(section.monthYearFormatted)
                        Spacer()
                        let count = _tournaments.map { $0.tournaments.count }.reduce(0,+)
                        Text("\(count.formatted()) tournoi" + count.pluralSuffix)
                    }
                }
                .headerProminence(.increased)
                .task {
                    if navigation.agendaDestination == .tenup
                        && dataStore.user.hasTenupClubs() == true
                        && _tournaments.isEmpty {
                        _gatherFederalTournaments(startDate: section)
                    }
                }
            }
        }
    }
    
    private func _gatherFederalTournaments(startDate: Date) {
//        isGatheringFederalTournaments = true
        Task {
            do {
                let clubs : [Club] = dataStore.user.clubsObjects()
                try await federalDataViewModel.gatherTournaments(clubs: clubs.filter { $0.code != nil }, startDate: startDate, endDate: startDate.endOfMonth)
            } catch {
                Logger.error(error)
//                self.error = error
            }
//            isGatheringFederalTournaments = false
        }
    }
    
    private func _nextMonths() -> [Date] {
        var result: [Date] = []
        var currentDate = Date().startOfMonth
        
        // Generate 100 future months
        for _ in 0..<12 {
            result.append(currentDate)
            currentDate = Calendar.current.date(byAdding: .month, value: 1, to: currentDate)!
        }
        
        return result
    }
    
    private func _listView(_ tournaments: [FederalTournamentHolder]) -> some View {
        ForEach(tournaments, id: \.holderId) { tournamentHolder in
            if let tournament = tournamentHolder as? Tournament {
                _tournamentView(tournament)
            } else if let federalTournament = tournamentHolder as? FederalTournament {
                _federalTournamentView(federalTournament)
            }
        }
    }
    
    private func _tournamentView(_ tournament: Tournament) -> some View {
        NavigationLink(value: tournament) {
            TournamentCellView(tournament: tournament)
        }
        .contextMenu {
            Button {
                navigation.openTournamentInOrganizer(tournament)
            } label: {
                Label("Voir dans le gestionnaire", systemImage: "line.diagonal.arrow")
            }
        }
    }
    
    private func _federalTournamentView(_ federalTournament: FederalTournament) -> some View {
        TournamentCellView(tournament: federalTournament)
    }

}

//#Preview {
//    EventListView(tournaments: [], viewStyle: .calendar, sortAscending: true)
//}
