(ns auto-ap.views.pages.admin.vendors
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [re-frame.core :as re-frame]
            [reagent.core :as reagent]
            [clojure.string :as str]
            [auto-ap.subs :as subs]
            [auto-ap.events.admin.vendors :as events]
            [auto-ap.entities.vendors :as entity]
            [auto-ap.views.components.address :refer [address-field]]
            [auto-ap.views.components.modal :refer [modal]]
            [clojure.spec.alpha :as s]
            [auto-ap.views.utils :refer [login-url dispatch-value-change dispatch-event bind-field horizontal-field]]
            [cljs.reader :as edn]
            [auto-ap.routes :as routes]
            [bidi.bidi :as bidi]))

(defn invalid-fields [spec v]
  (set (mapcat :in (::s/problems (s/explain-data spec v)))))

(defn vendors-table []
  (let [vendors (re-frame/subscribe [::subs/vendors])
        editing-vendor (:editing @(re-frame/subscribe [::subs/admin]))]
    
    [:table {:class "table", :style {:width "100%"}}
     [:thead  
      [:tr  
       [:th "Name"]
       [:th "Email"]
       [:th "Invoice Reminders"]
       [:th]]]
     [:tbody (for [v @vendors]
               ^{:key (str (:id v))}
               [:tr {:on-click (dispatch-event [::events/edit (:id v)])
                     :style {"cursor" "pointer"}}
                [:td (:name v)]
                [:td (:primary-email v)]
                [:td (:invoice-reminder-schedule v)]
                [:td
                 (when (:primary-email v)
                   [:button.button.is-primary.is-outlined

                    {:on-click (dispatch-event [::events/remind (:id v)])
                     :href "#"}
                    [:span.icon [:i.fa.fa-share-square]] [:span "Send Reminder"]])]])]]))

(defn danger-for [[dom {:keys [field subscription class] :as keys} & rest]]
  (let [keys (assoc keys :class (str class
                                     (when (not (s/valid? field (field subscription)))
                                       " is-danger")))
        keys (dissoc keys :field :subscription)]
    (vec (concat [dom keys] rest))))



(defn edit-dialog []
  (let [editing-vendor (:vendor @(re-frame/subscribe [::subs/admin]))
        companies-by-id @(re-frame/subscribe [::subs/companies-by-id])]
   
    [modal {:title [:span (if (:id editing-vendor)
                            (str "Edit " (or (:name editing-vendor) "<vendor>"))
                            (str "Add " (or (:name editing-vendor) "<new vendor>")))
                    (when (:error editing-vendor)
                      [:span.icon.has-text-danger
                       [:i.fa.fa-exclamation-triangle]])]
            :foot [:button.button.is-primary {:on-click (fn [] (re-frame/dispatch [::events/save]))
                                              :disabled (when (not (s/valid? ::entity/vendor editing-vendor ))
                                                          "disabled")}
                   [:span "Save"] 
                   (when (:saving? editing-vendor)
                     [:span.icon
                      [:i.fa.fa-spin.fa-spinner]])]
            :hide-event [::events/edit nil]}
     
     [horizontal-field
      [:label.label "Name"]
      [:div.control
       [bind-field
        [:input.input {:type "text"
                       :field :name
                       :spec ::entity/name
                       :event ::events/change
                       :subscription editing-vendor}]]]]
     
     [horizontal-field
      [:label.label "Code"]
      [:div.control

       [bind-field
        [:input.input.is-expanded {:type "text"
                                   :field :code
                                   :spec ::entity/code
                                   :event ::events/change
                                   :subscription editing-vendor}]]
       [:p.help "The vendor code is used for invoice parsing. Only one vendor at a time can use a code"]]] 

     [:h2.subtitle "Address"]
     [address-field {:field [:address]
                     :event ::events/change
                     :subscription editing-vendor}]
     
     
     
     [:h2.subtitle "Contact"]
     [horizontal-field
      [:label.label "Primary"]
      [:div.control.has-icons-left
       [bind-field
        [:input.input.is-expanded {:type "text"
                                   :field :primary-contact
                                   :spec ::entity/primary-contact
                                   :event ::events/change
                                   :subscription editing-vendor}]]
       [:span.icon.is-small.is-left
        [:i.fa.fa-user]]]

      [:div.control.has-icons-left
       [:span.icon.is-small.is-left
        [:i.fa.fa-envelope]]
       [bind-field
        [:input.input {:type "email"
                       :field :primary-email
                       :spec ::entity/primary-email
                       :event ::events/change
                       :subscription editing-vendor}]]]

      [:div.control.has-icons-left
       [bind-field
        [:input.input {:type "phone"
                       :field :primary-phone
                       :spec ::entity/primary-phone
                       :event ::events/change
                       :subscription editing-vendor}]]
       [:span.icon.is-small.is-left
        [:i.fa.fa-phone]]]]
     
     [horizontal-field
      [:label.label "Secondary"]
      [:div.control.has-icons-left
       [bind-field
        [:input.input.is-expanded {:type "text"
                                   :field :secondary-contact
                                   :spec ::entity/secondary-contact
                                   :event ::events/change
                                   :subscription editing-vendor}]]
       [:span.icon.is-small.is-left
        [:i.fa.fa-user]]]
      [:div.control.has-icons-left
       [:span.icon.is-small.is-left
        [:i.fa.fa-envelope]]
       [bind-field
        [:input.input {:type "email"
                       :field :secondary-email
                       :spec ::entity/secondary-email
                       :event ::events/change
                       :subscription editing-vendor}]]]
      [:div.control.has-icons-left
       [bind-field
        [:input.input {:type "phone"
                       :field :secondary-phone
                       :spec ::entity/secondary-phone
                       :event ::events/change
                       :subscription editing-vendor}]]
       [:span.icon.is-small.is-left
        [:i.fa.fa-phone]]]]
     
     [horizontal-field
      [:label.label "Invoice Reminders"]
      [:div.control
       [:label.radio 
        [bind-field
         [:input {:type "radio"
                  :name "schedule"
                  :value "Weekly"
                  :field :invoice-reminder-schedule
                  :spec ::entity/invoice-reminder-schedule
                  :event ::events/change
                  :subscription editing-vendor}]]
        " Send weekly"]

       [:label.radio 
        [bind-field
         [:input {:type "radio"
                  :name "schedule"
                  :value "Never"
                  :field :invoice-reminder-schedule
                  :spec ::entity/invoice-reminder-schedule
                  :event ::events/change
                  :subscription editing-vendor}]]
        " Never"]]]
     

     [:h2.subtitle "Clients"]

     [horizontal-field
      nil
      [:div.control
       [:div.select.is-expanded
        [bind-field
         [:select {:type "select"
          :field :new-relationship-company
          :event ::events/change
          :subscription editing-vendor}
          (for [company @(re-frame/subscribe [::subs/companies])]
            [:option {:value (:id company)} (:name company)])]]]]
      [:div.control
       [bind-field
        [:input.input {:type "text"
                       :field :new-relationship-account-number
                       :subscription editing-vendor
                       :event ::events/change
                       :placeholder "Account number"}]]]
      [:div.control
       [:button.button.is-primary
        {:on-click (dispatch-event [::events/add-relationship])}
        [:span.icon
         [:i.fa.fa-plus]]]]]
     [horizontal-field
      nil
      [:ul
       (for [[i r] (map vector (range) (:relationships editing-vendor))]
         ^{:key i}
         [:li
          (:name (companies-by-id (js/parseInt (:company-id r)))) ": "
          (:account-number r)
          [:a
           {:on-click (dispatch-event [::events/remove-relationship i])}
           [:span.icon
            [:i.fa.fa-times]]]])]] 
     
     
     (when (:saving? editing-vendor) [:div.is-overlay {:style {"backgroundColor" "rgba(150,150,150, 0.5)"}}])]))

(defn admin-vendors-page []
  [(with-meta
     (fn []
       [:div.inbox-messages
        (when-let [banner (:banner @(re-frame/subscribe [::subs/admin]))]
          [:div.notification banner])
        (let [vendors (re-frame/subscribe [::subs/vendors])
              editing-vendor (:vendor @(re-frame/subscribe [::subs/admin]))]
          
          
          [:div
           [:h1.title "Vendors"]
           [vendors-table]

           [:div.is-pulled-right
            [:a.button.is-primary.is-large {:on-click (dispatch-event [::events/new])} "New vendor"]]

           (when editing-vendor
             [edit-dialog])])])
     {:component-did-mount (fn []
                             (re-frame/dispatch [::events/mounted]))})])
