//
//  CourtView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 23/04/2024.
//

import SwiftUI
import LeStorage

struct CourtView: View {
    @EnvironmentObject var dataStore: DataStore
    @Bindable var court: Court
    @State private var name: String = ""
    
    init(court: Court) {
        self.court = court
        _name = State(wrappedValue: court.name ?? "")
    }
    
    var body: some View {
        Form {
            Section {
                LabeledContent {
                    TextField("Nom", text: $name)
                        .autocorrectionDisabled()
                        .keyboardType(.alphabet)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: .infinity)
                        .onSubmit {
                            court.name = name
                            if name.isEmpty {
                                court.name = nil
                            }
                            do {
                                try dataStore.courts.addOrUpdate(instance: court)
                            } catch {
                                Logger.error(error)
                            }
                        }
                } label: {
                    Text("Nom du terrain")
                }
            } footer: {
                if court.name?.isEmpty == false {
                    FooterButtonView("nom par défaut") {
                        name = ""
                        court.name = nil
                        do {
                            try dataStore.courts.addOrUpdate(instance: court)
                        } catch {
                            Logger.error(error)
                        }
                    }
                }
            }
            
            Section {
                Toggle(isOn: $court.exitAllowed) {
                    Text("Sortie autorisée")
                }
                Toggle(isOn: $court.indoor) {
                    Text("Terrain intérieur")
                }
            }
        }
        .onChange(of: [court.indoor, court.exitAllowed]) {
            do {
                try dataStore.courts.addOrUpdate(instance: court)
            } catch {
                Logger.error(error)
            }
        }
        .navigationTitle(court.courtTitle())
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}

//#Preview {
//    CourtView(court: Court.mock())
//}
