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

import SwiftUI
import CoreLocation
import LeStorage
import StoreKit

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 private var showProductIds: Bool = false
    
//    @State var isConnected: Bool = false
    
    enum UmpireScreen {
        case login
    }
    
    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")
                        }.simultaneousGesture(
                            LongPressGesture()
                                .onEnded { _ in
                                    self.showProductIds = true
                                }
                        )
                        
                        .highPriorityGesture(
                            TapGesture()
                                .onEnded { _ in
                                    self.showSubscriptions = true
                                }
                        )

                    }
                }
                
                if StoreCenter.main.isAuthenticated {
                    NavigationLink {
                        AccountView(user: dataStore.user) {  }
                    } label: {
                        AccountRowView(userName: dataStore.user.username)
                    }
                } else {
                    NavigationLink(value: UmpireScreen.login) {
                        AccountRowView(userName: dataStore.user.username)
                    }
                }
                
                let currentPlayerData = dataStore.user.currentPlayerData()
                Section {
                    if let currentPlayerData {
                        //todo palmares
                        ImportedPlayerView(player: currentPlayerData, showProgression: true)
//                        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 {
//                        UmpireStatisticView()
//                    } label: {
//                        Text("Statistiques de participations")
//                    }
//                }
//                

                Section {
                    @Bindable var user = dataStore.user
                    Picker(selection: $user.loserBracketMode) {
                        ForEach(LoserBracketMode.allCases) {
                            Text($0.localizedLoserBracketMode()).tag($0)
                        }
                    } label: {
                        Text("Position des perdants")
                    }
                    .onChange(of: user.loserBracketMode) {
                        dataStore.saveUser()
                    }
                } header: {
                    Text("Matchs de classement")
                }
                
                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 {
//                    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) {
                    NetworkStatusView()
//                    if StoreCenter.main.collectionsCanSynchronize {
//                        Image(systemName: "checkmark.icloud")
//                    } else {
//                        Image(systemName: "icloud.slash")
//                    }
                }
#endif
            }
            .sheet(isPresented: self.$showSubscriptions, content: {
                NavigationStack {
                    SubscriptionView(isPresented: self.$showSubscriptions)
                        .environment(\.colorScheme, .light)
                }
            })
            .sheet(isPresented: self.$showProductIds, content: {
                ProductIdsView()
            })
            .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?.computedLicense
                            if user.clubsObjects().contains(where: { $0.code == player.clubCode }) == false {
                                let userClub = Club.findOrCreate(name: player.clubName!, code: player.clubCode)
                                if userClub.hasBeenCreated(by: StoreCenter.main.userId) {
                                    do {
                                        try dataStore.clubs.addOrUpdate(instance: userClub)
                                    } catch {
                                        Logger.error(error)
                                    }
                                }
                                user.setUserClub(userClub)
                            }
                            self.dataStore.saveUser()
                        }
                    })
                }
                .task {
                    do {
                        try await dataStore.clubs.loadDataFromServerIfAllowed()
                    } catch {
                        Logger.error(error)
                    }
                }
            }
            .navigationDestination(for: UmpireScreen.self) { screen in
                switch screen {
                case .login:
                    LoginView {_ in }
                }
            }
        }
    }
    
}

struct AccountRowView: View {
    @EnvironmentObject var dataStore: DataStore

    var userName: String
    var body: some View {
        
        let isAuthenticated = StoreCenter.main.isAuthenticated
        LabeledContent {
            if isAuthenticated {
                Text(self.userName)
            } else if StoreCenter.main.userName != nil {
                Image(systemName: "xmark.circle.fill")
                    .foregroundStyle(.logoRed)
            }
        } label: {
            Label("Mon compte", systemImage: "person.fill")
            if isAuthenticated && dataStore.user.email.isEmpty == false {
                Text(dataStore.user.email)
            }
        }
    }
}

struct ProductIdsView: View {
    
    @State var transactions: [StoreKit.Transaction] = []
    
    var body: some View {
        VStack {
            List {
                LabeledContent("count", value: String(self.transactions.count))
                ForEach(self.transactions) { transaction in
                    if #available(iOS 17.2, *) {
                        if let offer = transaction.offer {
                            LabeledContent(transaction.productID, value: "\(offer.type)")
                        } else {
                            LabeledContent(transaction.productID, value: "no offer")
                        }
                    } else {
                        Text("need ios 17.2")
                    }
                }
            }.onAppear {
                Task {
                    self.transactions = Array(Guard.main.purchasedTransactions)
                }
            }
        }
    }
    
}

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