//
//  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 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)
                    
                }

                #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 {
                    Link(destination: URLs.main.url) {
                        Text("Accéder au site Padel Club")
                    }
                }
                
                Section {
                    NavigationLink {
                        SelectablePlayerListView()
                    } label: {
                        Label("Rechercher un joueur", systemImage: "person.fill.viewfinder")
                    }
                }
                
                Section {
                    NavigationLink {
                        RankCalculatorView()
                    } label: {
                        Label("Calculateur de points", systemImage: "scalemass")
                    }
                }

                Section {
                    NavigationLink {
                        GlobalSettingsView()
                    } label: {
                        Label("Formats de jeu par défaut", systemImage: "megaphone")
                    }
                    NavigationLink {
                        DurationSettingsView()
                    } label: {
                        Label("Définir les durées moyennes", systemImage: "deskclock")
                    }
                } footer: {
                    Text("Vous pouvez définir vos propres estimations de durées de match en fonction du format de jeu.")
                }
                
                Section {
                    Link("Accéder au guide de la compétition de la FFT", destination: URLs.padelRules.url)
                }
            }
            .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()
//}
