//
//  EventSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/05/2024.
//

import SwiftUI
import LeStorage

struct EventSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @Bindable var event: Event
    @State private var eventName: String = ""
    @FocusState private var textFieldIsFocus: Bool

    init(event: Event) {
        self.event = event
        _eventName = State(wrappedValue: event.name ?? "")
    }
    
    var body: some View {
        Form {
            Section {
                TextField("Nom de l'événement", text: $eventName, axis: .vertical)
                    .lineLimit(2)
                    .keyboardType(.alphabet)
                    .multilineTextAlignment(.leading)
                    .frame(maxWidth: .infinity)
                    .focused($textFieldIsFocus)
            } footer: {
                if eventName.isEmpty == false {
                    FooterButtonView("effacer le nom") {
                        eventName = ""
                        event.name = nil
                        _save()
                    }
                }
            }
        }
        .toolbar {
            if textFieldIsFocus {
                ToolbarItem(placement: .keyboard) {
                    HStack {
                        Spacer()
                        Button("Valider") {
                            textFieldIsFocus = false
                            if eventName.trimmed.isEmpty == false {
                                event.name = eventName.trimmed
                            } else {
                                event.name = nil
                            }
                            _save()
                        }
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
    }
    
    private func _save() {
        do {
            try dataStore.events.addOrUpdate(instance: event)
        } catch {
            Logger.error(error)
        }
    }
}
