(ns auto-ap.views.pages.pos.form
  (:require
   [auto-ap.forms :as forms]
   [auto-ap.subs :as subs]
   [auto-ap.views.components.layouts :as layouts]
   [auto-ap.views.components.money-field :refer [money-field]]
   [auto-ap.views.utils
    :refer [date->str date-picker dispatch-event standard]]
   [re-frame.core :as re-frame]
   [auto-ap.forms.builder :as form-builder]
   [auto-ap.views.components :as com]))


(re-frame/reg-event-db
 ::editing
 (fn [db [_ which]]
   (let [which (update which :date #(date->str % standard))]
     (forms/start-form db ::form which))))


(defn form []
  [layouts/side-bar {:on-close   (dispatch-event [::forms/form-closing ::form ])}
   (let [{:keys [data]} @(re-frame/subscribe [::forms/form ::form])]
     [form-builder/builder {:submit-event [::saving ]
                            :id           ::form}
      [form-builder/section {:title "Sales Order"}
       [:div
        "Order " (:id data)
        (when (:reference-link data)
          [:a {:href   (:reference-link data)
               :target "_new"}
           [:span.icon 
            [:i.fa.fa-external-link
             ]]])]
       (when-not @(re-frame/subscribe [::subs/client])
         [form-builder/field-v2 {:field :client}
          "Client"
          [com/entity-typeahead {:entities     @(re-frame/subscribe [::subs/clients])
                                 :entity->text :name
                                 :disabled     true}]])


       [form-builder/field-v2 {:field :date}
        "Date"
        [date-picker {:output   :cljs-date
                      :disabled true}]]
       [form-builder/field-v2 {:field :total}
        "Total"
        [money-field {:disabled true}]]
       [form-builder/field-v2 {:field :tax}
        "Tax"
        [money-field {:disabled true}]
        [form-builder/field-v2 {:field :discount}
         "Discount"
         [money-field {:disabled true}]]]

       [form-builder/field-v2 {:field :returns}
        "Returns"
        [money-field {:disabled true}]]

       [form-builder/field-v2 {:field :service-charge}
        "Service Charge"
        [money-field {:disabled true}]]

       [form-builder/field-v2 {:field :tip}
        "Tip"
        [money-field {:disabled true}]]

       [form-builder/section {:title "Charges"}
        [:ul 
         (for [charge (:charges data)]
           ^{:key (:id charge)}
           [:li [:span (:type-name charge) ": " (:total charge)
                 (when (:reference-link charge)
                   [:a {:href (:reference-link charge) :target "_new"}
                    [:span.icon 
                     [:i.fa.fa-external-link
                      ]]])]])]]

       [form-builder/section {:title "Line Items"}
        [:ul 
         (for [line-item (:line-items data)]
           ^{:key (:item-name line-item)}
           [:li (:item-name line-item) ": " (:total line-item) [:span.tag (:category line-item)]])]]]])])

