//
//  TournamentGeneralSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 18/04/2024.
//

import SwiftUI
import LeStorage

struct TournamentGeneralSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    
    var tournament: Tournament
    @State private var tournamentName: String = ""
    @State private var entryFee: Double? = nil
    @FocusState private var focusedField: Tournament.CodingKeys?
    
    init(tournament: Tournament) {
        self.tournament = tournament
        _tournamentName = State(wrappedValue: tournament.name ?? "")
        _entryFee = State(wrappedValue: tournament.entryFee)
    }
    
    var body: some View {
        @Bindable var tournament = tournament
        Form {            
            Section {
                TournamentDatePickerView()
                TournamentDurationManagerView()
            }
            
            Section {
                TournamentLevelPickerView()
            }
            
            Section {
                LabeledContent {
                    TextField(tournament.isFree() ? "Gratuite" : "Inscription", value: $entryFee, format: .currency(code: Locale.current.currency?.identifier ?? "EUR"))
                        .keyboardType(.decimalPad)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: .infinity)
                        .focused($focusedField, equals: ._entryFee)
                } label: {
                    Text("Inscription")
                }
            }
            
            Section {
                TextField("Nom du tournoi", text: $tournamentName, axis: .vertical)
                    .lineLimit(2)
                    .frame(maxWidth: .infinity)
                    .keyboardType(.alphabet)
                    .focused($focusedField, equals: ._name)
            }
        }
        .toolbarBackground(.visible, for: .navigationBar)
        .toolbar {
            if focusedField != nil {
                ToolbarItem(placement: .keyboard) {
                    HStack {
                        Spacer()
                        Button("Valider") {
                            if focusedField == ._name {
                                if tournamentName.trimmed.isEmpty {
                                    tournament.name = nil
                                } else {
                                    tournament.name = tournamentName
                                }
                            } else if focusedField == ._entryFee {
                                tournament.entryFee = entryFee
                            }
                            focusedField = nil
                        }
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
        .onChange(of: tournament.startDate) {
            _save()
        }
        .onChange(of: tournament.entryFee) {
            _save()
        }
        .onChange(of: tournament.name) {
            _save()
        }
        .onChange(of: tournament.dayDuration) {
            _save()
        }
        .onChange(of: [
            tournament.federalCategory,
        ]) {
            _save()
        }
        .onChange(of: [
            tournament.federalLevelCategory,
        ]) {
            _save()
        }
        .onChange(of: [
            tournament.federalAgeCategory,
        ]) {
            _save()
        }
        .onChange(of: [
            tournament.groupStageSortMode,
        ]) {
            _save()
        }
    }
    
    private func _save() {
        do {
            try dataStore.tournaments.addOrUpdate(instance: tournament)
        } catch {
            Logger.error(error)
        }
    }
}
