//
//  CountdownFormView.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 27/01/2023.
//

import SwiftUI


struct CountdownFormView : View {

    enum CountdownField: Int, Hashable {
        case minutes
        case seconds
        case name
    }
    
    @FocusState private var focusedField: CountdownField?
    
    @EnvironmentObject var model: TimerModel

    var secondsBinding: Binding<String>
    var minutesBinding: Binding<String>
    var nameBinding: Binding<String>

    var imageBinding: Binding<CoolPic>

    var repeatCountBinding: Binding<Int16>

//    var textFieldIsFocused: FocusState<Bool>.Binding

    var intervalRepeatBinding: Binding<Int>? = nil

    var body: some View {
        Form {
            Section("Duration") {
                TextField("Minutes", text: minutesBinding)
                    .keyboardType(.numberPad)
                    .focused($focusedField, equals: .minutes)
                    .onSubmit {
                        self.focusNextField($focusedField)
                    }
                TextField("Seconds", text: secondsBinding)
                    .keyboardType(.numberPad)
                    .focused($focusedField, equals: .seconds)
                    .onSubmit {
                        self.focusNextField($focusedField)
                    }
                TextField("Name (activates tracking)", text: nameBinding)
                    .focused($focusedField, equals: .name)
                    .onSubmit {
                        self.focusedField = nil
                    }
            }

            SoundImageFormView(
                imageBinding: imageBinding,
                repeatCountBinding: repeatCountBinding)
                .environmentObject(self.model)
        }.toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                Button {
                    self.focusedField = nil
                } label: {
                    Image(systemName: "keyboard.chevron.compact.down")
                }
                Spacer()
                Button {
                    self.focusPreviousField($focusedField)
                } label: {
                    Image(systemName: "chevron.up")
                }
                Button {
                    self.focusNextField($focusedField)
                } label: {
                    Image(systemName: "chevron.down")
                }
            }
        }
        
    }
    
}

struct CountdownFormView_Previews: PreviewProvider {
    
    @FocusState static var textFieldIsFocused: Bool
    
    static var previews: some View {
        CountdownFormView(
            secondsBinding: .constant(""),
            minutesBinding: .constant(""),
            nameBinding: .constant(""),
            imageBinding: .constant(.pic3),
            repeatCountBinding: .constant(2),
            intervalRepeatBinding: .constant(2))
        .environmentObject(TimerModel())
    }
}
