//
//  StepperView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 14/02/2024.
//

import SwiftUI

struct StepperView: View {
    
    var title: String? = nil
    @Binding var count: Int
    var step: Int = 1
    var minimum: Int? = nil
    var maximum: Int? = nil
    
    var countChanged: (() -> ())? = nil

    var body: some View {
        VStack {
            HStack(spacing: 8) {
                Button(action: {
                    self._subtract()
                }, label: {
                    Image(systemName: "minus.circle")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24)
                })
                .disabled(_minusIsDisabled())
                .buttonStyle(.borderless)

                TextField("00", value: $count, format: .number)
                    .keyboardType(.numberPad)
                    .fixedSize()
//                    .font(.title2)
                    .monospacedDigit()
                    .multilineTextAlignment(.center)
                    .onSubmit {
                        if let minimum, count < minimum {
                            count = minimum
                        } else if let maximum, count > maximum {
                            count = maximum
                        }
                    }
                Button(action: {
                    self._add()
                }, label: {
                    Image(systemName: "plus.circle")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24)
                })
                .disabled(_plusIsDisabled())
                .buttonStyle(.borderless)
            }
            if let title {
                Text(title + count.pluralSuffix).font(.caption)
            }
        }
        .multilineTextAlignment(.trailing)
    }
    
    fileprivate func _minusIsDisabled() -> Bool {
        count <= (minimum ?? 0)
    }

    fileprivate func _plusIsDisabled() -> Bool {
        count >= (maximum ?? 100_000)
    }

    fileprivate func _add() {
        if let maximum, self.count + 1 > maximum {
            return
        }
        self.count += step
        self.countChanged?()
    }
    
    fileprivate func _subtract() {
        if let minimum, self.count - 1 < minimum {
            return
        }
        self.count -= step
        self.countChanged?()
    }
    
}

//#Preview {
//    StepperView(title: "poule", count: .constant(1))
//}
