//
//  CashierSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/04/2024.
//

import SwiftUI
import LeStorage

struct CashierSettingsView: View {
    
    @EnvironmentObject var dataStore: DataStore
    @State private var entryFee: Double? = nil
    @Bindable var tournament: Tournament
    @FocusState private var focusedField: Tournament.CodingKeys?
    let priceTags: [Double] = [15.0, 20.0, 25.0]
    
    init(tournament: Tournament) {
        self.tournament = tournament
        _entryFee = State(wrappedValue: tournament.entryFee)
    }
    
    var body: some View {
        List {
            Section {
                TextField(tournament.isFree() ? "Gratuite" : "Inscription", value: $entryFee, format: .currency(code: Locale.defaultCurrency()))
                    .keyboardType(.decimalPad)
                    .multilineTextAlignment(.trailing)
                    .frame(maxWidth: .infinity)
                    .focused($focusedField, equals: ._entryFee)
            } header: {
                Text("Prix de l'inscription")
            } footer: {
                Text("Si vous souhaitez que Padel Club vous aide à suivre les encaissements, indiquer un prix d'inscription. Sinon Padel Club vous aidera à suivre simplement l'arrivée et la présence des joueurs.")
            }

            let players = tournament.selectedPlayers()

            if players.anySatisfy({ $0.hasArrived == false }) {
                Section {
                    RowButtonView("Tout le monde est arrivé", role: .destructive) {
                        players.forEach { player in
                            player.hasArrived = true
                        }
                        _save(players: players)
                    }
                } footer: {
                    Text("Indique tous les joueurs sont là")
                }
            }

            if players.anySatisfy({ $0.hasArrived == true }) {
                Section {
                    RowButtonView("Personne n'est là", role: .destructive) {
                        players.forEach { player in
                            player.hasArrived = false
                        }
                        _save(players: players)
                    }
                } footer: {
                    Text("Indique qu'aucun joueur n'est arrivé")
                }
            }

            if players.anySatisfy({ $0.hasPaid() == false }) {
                Section {
                    RowButtonView("Tout le monde a réglé", role: .destructive) {
                        players.forEach { player in
                            if player.hasPaid() == false {
                                player.paymentType = .gift
                            }
                        }
                        _save(players: players)
                    }
                } footer: {
                    Text("Passe tous les joueurs qui n'ont pas réglé en offert")
                }
            }
            
            if players.anySatisfy({ $0.hasPaid() == true }) {
                Section {
                    RowButtonView("Personne n'a réglé", role: .destructive) {
                        players.forEach { player in
                            player.paymentType = nil
                        }
                        _save(players: players)
                    }
                } footer: {
                    Text("Remet à zéro le type d'encaissement de tous les joueurs")
                }
            }
        }
        .navigationBarBackButtonHidden(focusedField != nil)
        .toolbarBackground(.visible, for: .navigationBar)
        .toolbar {
            if focusedField != nil {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Annuler", role: .cancel) {
                        focusedField = nil
                    }
                }

                ToolbarItem(placement: .keyboard) {
                    HStack {
                        if tournament.isFree() {
                            ForEach(priceTags, id: \.self) { priceTag in
                                Button(priceTag.formatted(.currency(code: Locale.defaultCurrency()))) {
                                    entryFee = priceTag
                                    tournament.entryFee = priceTag
                                    focusedField = nil
                                }
                                .buttonStyle(.bordered)
                            }
                        } else {
                            Button("Gratuit") {
                                entryFee = nil
                                tournament.entryFee = nil
                                focusedField = nil
                            }
                            .buttonStyle(.bordered)

                        }
                        Spacer()
                        Button("Valider") {
                            tournament.entryFee = entryFee
                            focusedField = nil
                        }
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
        .onChange(of: tournament.entryFee) {
            _save()
        }
    }
    
    private func _save(players: [PlayerRegistration]) {
        tournament.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
    }
    
    private func _save() {
        dataStore.tournaments.addOrUpdate(instance: tournament)
    }
}

//#Preview {
//    CashierSettingsView(tournaments: [])
//}
