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

import SwiftUI
import LeStorage

struct ToolboxView: View {
    @EnvironmentObject var dataStore: DataStore
    
    @Environment(NavigationViewModel.self) private var navigation: NavigationViewModel
    @State private var didResetApiCalls: Bool = false
    
    var lastDataSource: String? {
        dataStore.appSettings.lastDataSource
    }
    
    var _mostRecentDateAvailable: Date? {
        SourceFileManager.shared.mostRecentDateAvailable
    }
    
    var _lastDataSourceDate: Date? {
        guard let lastDataSource else { return nil }
        return URL.importDateFormatter.date(from: lastDataSource)
    }
    
    var body: some View {
        @Bindable var navigation = navigation
        NavigationStack(path: $navigation.toolboxPath) {
            List {
                
                Section {
                    Text("Version de l'application").badge(PadelClubApp.appVersion)
                        .onTapGesture(count: 5) {
                            StoreCenter.main.resetApiCalls()
                            didResetApiCalls = true
                        }
                    
                    SupportButtonView(contentIsUnavailable: false)
                    Link(destination: URLs.main.url) {
                        Text("Accéder au site Padel Club")
                    }
                    .contextMenu {
                        ShareLink(item: URLs.main.url)
                    }
                }
                

                #if DEBUG
                
                Section {
                    NavigationLink("Settings") {
                        DebugSettingsView()
                    }
                    NavigationLink("API calls") {
                        APICallsListView()
                    }
                }
                
                Section {
                    RowButtonView("Reset ALL API Calls") {
                        StoreCenter.main.resetApiCalls()
                        Logger.log("Api calls reset")
                    }
                }
                Section {
                    RowButtonView("Fix Names") {
                        
                        for tournament in dataStore.tournaments {
                            
                            let store = tournament.tournamentStore
                            let playerRegistrations = store.playerRegistrations
                            playerRegistrations.forEach { player in
                                player.firstName = player.firstName.trimmed.capitalized
                                player.lastName = player.lastName.trimmed.uppercased()
                            }
                            
                            do {
                                try store.playerRegistrations.addOrUpdate(contentOfs: playerRegistrations)
                            } catch {
                                Logger.error(error)
                            }
                        }
                        
                    }
                }
                
                Section {
                    RowButtonView("Delete teams") {
                        
                        for tournament in DataStore.shared.tournaments {
                            
                            let store: TournamentStore = tournament.tournamentStore
                            
                            let teamRegistrations = store.teamRegistrations.filter({ $0.tournamentObject() == nil })
                            do {
                                try store.teamRegistrations.delete(contentOfs: teamRegistrations)
                            } catch {
                                Logger.error(error)
                            }
                        }
                    }
                }
                
                Section {
                    // TODO
                    RowButtonView("Delete players") {
                        
                        for tournament in DataStore.shared.tournaments {
                            let store: TournamentStore = tournament.tournamentStore
                            
                            let playersRegistrations = store.playerRegistrations.filter({ $0.team() == nil })
                            do {
                                try store.playerRegistrations.delete(contentOfs: playersRegistrations)
                            } catch {
                                Logger.error(error)
                            }
                        }
                        
                    }

                }
                #endif

                Section {
                    NavigationLink {
                        PadelClubView()
                    } label: {
                        if let _lastDataSourceDate {
                            LabeledContent {
                                Image(systemName: "checkmark.circle.fill")
                                    .foregroundStyle(.green)
                            } label: {
                                Text(_lastDataSourceDate.monthYearFormatted)
                                Text("Classement mensuel utilisé")
                            }
                        } else {
                            LabeledContent {
                                Image(systemName: "xmark.circle.fill")
                                    .tint(.logoRed)
                            } label: {
                                if let _mostRecentDateAvailable {
                                    Text(_mostRecentDateAvailable.monthYearFormatted)
                                } else {
                                    Text("Aucun")
                                }
                                Text("Classement mensuel disponible")
                            }
                        }
                    }
                }
                
                Section {
                    NavigationLink {
                        SelectablePlayerListView()
                    } label: {
                        Label("Rechercher un joueur", systemImage: "person.fill.viewfinder")
                    }

                    NavigationLink {
                        RankCalculatorView()
                    } label: {
                        Label("Calculateur de points", systemImage: "scalemass")
                    }
                }
                
                Section {
                    Link("Accéder au guide de la compétition", destination: URLs.padelRules.url)
                    Link("Formulaire de décharge des temps de repos", destination: URLs.restingDischarge.url)
                } header: {
                    Text("Documents fédéraux")
                }

            }
            .overlay(alignment: .bottom) {
                if didResetApiCalls {
                    Label("failed api calls deleted", systemImage: "checkmark")
                        .toastFormatted()
                        .deferredRendering(for: .seconds(3))
                        .onAppear {
                            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                                didResetApiCalls = false
                            }
                        }
                }
            }

            .navigationTitle(TabDestination.toolbox.title)
        }
    }
}

//#Preview {
//    ToolboxView()
//}
