(ns auto-ap.views.components.money-field
  (:require [reagent.core :as r]
            [clojure.string :as str]))

(defn money-field [{:keys [min max disabled on-change value]}]
  (let [parsed-amount (r/atom {:parsed value
                               :raw (str value)})]
    (fn [{:keys [min max disabled on-change value]}]
      [:input.input {:type "number"
                     :disabled disabled 
                     :on-change (fn [e]
                                  (let [raw (.. e -target -value)
                                        new-value (when (and raw (not (str/blank? raw)))
                                                    (js/parseFloat raw))]
                                    (swap! parsed-amount assoc
                                           :raw raw
                                           :parsed new-value)
                                    (when (not= value new-value)
                                      (on-change new-value))))
                     :value (:raw @parsed-amount)
                     :min min
                     :max max
                     :step "0.01"}])))
