(ns auto-ap.views.components.percentage-field
  (:require [reagent.core :as r]
            [clojure.string :as str]
            [react :as react]))
(def good-% #"^\d{1,3}(?:\.\d{1,4})?$") 

(defn -percentage-field [{:keys [min max disabled on-blur on-change value class style placeholder]}]
  (let [[ parsed-amount set-parsed-amount] (react/useState {:parsed value
                                                            :raw    (cond
                                                                      (str/blank? value)
                                                                      ""

                                                                      (js/Number.isNaN (js/parseFloat value))
                                                                      ""

                                                                      :else
                                                                      (str (js/parseFloat value)))})]
    [:div.control.has-icons-left 
     [:input.input {:type      "text"
                    :disabled  disabled 
                    :placeholder placeholder
                    :class     class
                    :on-change (fn [e]
                                 (set-parsed-amount
                                  (assoc parsed-amount :raw (.. e -target -value))))
                    :value     (or (:raw parsed-amount)
                                   "")
                    :on-blur (fn []
                               (let [raw (:raw parsed-amount)]
                                 (if (re-find good-% raw)
                                   (let [new-value (when (and raw
                                                              (not (str/blank? raw))
                                                              (re-find good-% raw))
                                                     (js/parseFloat raw))]
                                     (set-parsed-amount {:raw    raw
                                                         :parsed new-value})
                                     (when (not= value new-value)
                                       (on-change new-value)))

                                   (do 
                                     (set-parsed-amount {:raw    ""
                                                         :parsed nil})
                                     (on-change nil))))
                               (when on-blur
                                 (on-blur)))
                    :min       min
                    :max       max
                    :step      "0.01"
                    :style     (or style
                                   {:width "8em"})}]
     [:span.icon.is-left
      [:i.fa.fa-percent]]]))

(defn percentage-field []
  [:f> -percentage-field (r/props (r/current-component))])
