(ns auto-ap.views.pages.admin.vendors.table
  (:require 
   [re-frame.core :as re-frame]
   [reagent.core :as reagent]
   [auto-ap.subs :as subs]
   [auto-ap.status :as status]
   [auto-ap.views.components.vendor-dialog :refer [vendor-dialog] :as vendor-dialog]
   [auto-ap.views.components.grid :as grid]
   [auto-ap.views.utils :refer [login-url dispatch-value-change dispatch-event bind-field horizontal-field action-cell-width]]
   [auto-ap.views.components.buttons :as buttons]))

(re-frame/reg-event-fx
 ::params-changed
 (fn [{:keys [db]} [_ p]]
   {:db (assoc db ::params p)}))

(re-frame/reg-sub
 ::params
 (fn [db]
   (-> db ::params)))

(defn vendors-table [{:keys [status page]}]
  (let [params @(re-frame/subscribe [::params])
        accounts @(re-frame/subscribe [::subs/all-accounts-by-id])]
    
    [grid/grid {:status status
                :on-params-change (fn [p]
                                    (re-frame/dispatch [::params-changed p]))
                :params params
                :column-count 4}
     [grid/controls page]
     [grid/table {:fullwidth true}
      [grid/header
       [grid/row {}
        [grid/header-cell {} "Name"]
        [grid/header-cell {} "Email"]
        [grid/header-cell {} "Default Account"]
        [grid/header-cell {:style {:width (action-cell-width 1)}}]]]
      [grid/body
       (for [v (:data page)]
         ^{:key (str (:id v))}
         [grid/row {:class (:class v) :id (:id v)}
          [grid/cell {} (:name v)
           (let [total-usage (reduce + 0 (map :count (:usage v)))]
             (if (> total-usage 0 )
               [:div.mx-2.tag.is-info.is-light total-usage " usages, " (count (:usage v)) " clients" ]
               [:div.mx-2.tag.is-warning.is-light "Unused"]))]
          [grid/cell {} (:email (:primary-contact v))]
          [grid/cell {} (-> v :default-account :id accounts :name)]
          [grid/cell {}
           [buttons/fa-icon {:event [::vendor-dialog/started v]
                             :icon "fa-pencil"}]]])]]]))
