//
//  UmpireView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/03/2024.
//

import SwiftUI
import CoreLocation
import LeStorage

struct UmpireView: View {
    
    @Environment(NavigationViewModel.self) private var navigation: NavigationViewModel
    @EnvironmentObject var dataStore: DataStore
    
    @State private var presentSearchView: Bool = false
    @State private var showSubscriptions: Bool = false
    
//    @State var isConnected: 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.umpirePath) {
            List {
                
                PurchaseListView()

                if Guard.main.currentPlan != .monthlyUnlimited {
                    Section {
                        Button {
                            self.showSubscriptions = true
                        } label: {
                            Label("Les offres", systemImage: "bookmark.fill")
                        }
                    }
                }
                
                if self._isConnected() {
                    NavigationLink {
                        AccountView(user: dataStore.user) {  }
                    } label: {
                        AccountRowView(userName: dataStore.user.username)
                    }
                } else {
                    NavigationLink {
                        LoginView {_ in }
                    } label: {
                        AccountRowView(userName: dataStore.user.username)
                    }
                }
                
                let currentPlayerData = dataStore.user.currentPlayerData()
                Section {
                    if let currentPlayerData {
                        //todo palmares
                        ImportedPlayerView(player: currentPlayerData)
//                        NavigationLink {
//                            
//                        } label: {
//                            ImportedPlayerView(player: currentPlayerData)
//                        }
                    } else {
                        RowButtonView("Ma fiche joueur", systemImage: "person.bust") {
                            presentSearchView = true
                        }
                    }
                } footer: {
                    if dataStore.user.licenceId == nil {
                        Text("Si vous avez participé à un tournoi dans les 12 derniers mois, Padel Club peut vous retrouver.")
                    } else if let currentPlayerData {
                        Menu {
                            Button {
                                UIPasteboard.general.string = currentPlayerData.formattedLicense()
                            } label: {
                                Text("Copier ma licence")
                                Text(currentPlayerData.formattedLicense())
                            }
                            
                            Button("Supprimer ma fiche") {
                                dataStore.user.licenceId = nil
                                self.dataStore.saveUser()
                            }

                        } label: {
                            Text("options")
                                .foregroundStyle(Color.master)
                                .underline()
                        }
                    }
                }
                
                Section {
                    NavigationLink {
                        ClubsView()
                    } label: {
                        LabeledContent {
                            Text(dataStore.user.clubs.count.formatted())
                        } label: {
                            Label("Clubs favoris", systemImage: "house.and.flag")
                        }
                    }
                } footer: {
                    Text("Il s'agit des clubs qui sont utilisés pour récupérer les tournois tenup.")
                }
                
                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(.red)
                            } label: {
                                if let _mostRecentDateAvailable {
                                    Text(_mostRecentDateAvailable.monthYearFormatted)
                                } else {
                                    Text("Aucun")
                                }
                                Text("Classement mensuel disponible")
                            }
                        }
                    }
                }
                
//                Section {
//                    Text("Tenup ID")
//                }
//
//                Section {
//                    Text("Tournois")
//                }
//
//                Section {
//                    NavigationLink {
//
//                    } label: {
//                        Text("Favori")
//                    }
//                    NavigationLink {
//
//                    } label: {
//                        Text("Black list")
//                    }
//                }
            }
            .navigationTitle("Juge-Arbitre")
            .toolbar {
#if DEBUG
                ToolbarItem(placement: .topBarTrailing) {
                    if Store.main.collectionsCanSynchronize {
                        Image(systemName: "checkmark.icloud")
                    } else {
                        Image(systemName: "icloud.slash")
                    }
                }
#endif
            }
            .sheet(isPresented: self.$showSubscriptions, content: {
                NavigationStack {
                    SubscriptionView(isPresented: self.$showSubscriptions)
                }
            })
            .sheet(isPresented: $presentSearchView) {
                let user = dataStore.user
                NavigationStack {
                    SelectablePlayerListView(allowSelection: 1, searchField: user.firstName + " " + user.lastName, playerSelectionAction: { players in
                        if let player = players.first {
                            user.licenceId = player.license
                            if user.clubsObjects().contains(where: { $0.code == player.clubCode }) == false {
                                let userClub = Club.findOrCreate(name: player.clubName!, code: player.clubCode)
                                do {
                                    try dataStore.clubs.addOrUpdate(instance: userClub)
                                    user.setUserClub(userClub)
                                } catch {
                                    Logger.error(error)
                                }
                            }
                            self.dataStore.saveUser()
                        }
                    })
                }
                .task {
                    do {
                        try await dataStore.clubs.loadDataFromServerIfAllowed()
                    } catch {
                        Logger.error(error)
                    }
                }
            }
        }
    }
    
    fileprivate func _isConnected() -> Bool {
        return dataStore.user.username.count > 0 && Store.main.hasToken()
    }

}

struct AccountRowView: View {
    @EnvironmentObject var dataStore: DataStore

    var userName: String
    var body: some View {
        LabeledContent {
            if Store.main.hasToken() {
                Text(self.userName)
            } else {
                Image(systemName: "exclamationmark.circle.fill")
                    .foregroundStyle(.master)
            }
        } label: {
            Label(Store.main.userName() == nil ? "Créer votre compte Padel Club" : "Mon compte", systemImage: "person.fill")
            if dataStore.user.email.isEmpty == false {
                Text(dataStore.user.email)
            }
        }
    }
}

//#Preview {
//    UmpireView()
//}
