//
//  OngoingView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 24/04/2024.
//

import SwiftUI
import LeStorage

struct OngoingView: View {
    @Environment(NavigationViewModel.self) private var navigation: NavigationViewModel
    @EnvironmentObject var dataStore: DataStore
    @State private var sortByField: Bool = false
    let fieldSorting : [MySortDescriptor<Match>] = [.keyPath(\Match.courtIndex!), .keyPath(\Match.startDate!)]
    let defaultSorting : [MySortDescriptor<Match>] = [.keyPath(\Match.startDate!), .keyPath(\Match.courtIndex!)]

    var matches: [Match] {
        let sorting = sortByField ? fieldSorting : defaultSorting
        return dataStore.matches.filter({ $0.confirmed && $0.startDate != nil && $0.endDate == nil && $0.courtIndex != nil }).sorted(using: sorting, order: .ascending)
    }
    
    var body: some View {
        @Bindable var navigation = navigation
        NavigationStack(path: $navigation.ongoingPath) {
            let matches = matches.filter { $0.currentTournament()?.isDeleted == false }
            List {
                ForEach(matches) { match in
                    Section {
                        MatchRowView(match: match, matchViewStyle: .standardStyle)
                    } header: {
                        if let tournament = match.currentTournament() {
                            HStack {
                                Text(tournament.tournamentTitle(.short))
                                Spacer()
                                if let club = tournament.club() {
                                    Text("@" + club.clubTitle(.short))
                                }
                            }
                        } else {
                            Text("Pas de tournoi")
                        }
                    } footer: {
                        HStack {
                            if let tournament = match.currentTournament() {
                                Text(tournament.eventLabel())
                            }
#if DEBUG
                            Spacer()
                            FooterButtonView("copier l'id") {
                                let pasteboard = UIPasteboard.general
                                pasteboard.string = match.id
                            }
#endif
                        }
                    }
                }
            }
            .headerProminence(.increased)
            .overlay {
                if matches.isEmpty {
                    ContentUnavailableView("Aucun match en cours", systemImage: "figure.tennis", description: Text("Tous vos matchs en cours seront visibles ici, quelque soit le tournoi."))
                }
            }
            .navigationTitle("En cours")
            .toolbar(matches.isEmpty ? .hidden : .visible, for: .navigationBar)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Menu {
                        Picker(selection: $sortByField) {
                            Text("Trier par date").tag(false)
                            Text("Trier par terrain").tag(true)
                        } label: {
                            
                        }
                        #if DEBUG
                        Button("effacer les mauvais matchs") {
                            let bad = matches.filter({ $0.currentTournament() == nil })
                            do {
                                try dataStore.matches.delete(contentOfs: bad)
                            } catch {
                                Logger.error(error)
                            }
                        }
                        #endif
                        //todo
                        //presentFilterView.toggle()
                    } label: {
                        Image(systemName: "line.3.horizontal.decrease.circle")
                            .resizable()
                            .scaledToFit()
                            .frame(minHeight: 28)
                    }
                    //.symbolVariant(federalDataViewModel.areFiltersEnabled() ? .fill : .none)
                }
                ToolbarItem(placement: .status) {
                    if matches.isEmpty == false {
                        Text("\(matches.count) match" + matches.count.pluralSuffix)
                    }
                }
            }
        }
    }
}

//#Preview {
//    OngoingView()
//}
