(ns auto-ap.views.pages.admin.vendors.table
  (:require
   [auto-ap.views.components.buttons :as buttons]
   [auto-ap.views.components.grid :as grid]
   [auto-ap.views.components.vendor-dialog :as vendor-dialog]
   [auto-ap.views.pages.data-page :as data-page]
   [auto-ap.views.utils :refer [action-cell-width]]
   [re-frame.core :as re-frame]))

(defn vendors-table [{:keys [data-page]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])]
    [grid/grid {:data-page data-page
                :column-count 4}
     [grid/controls data]
     [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 data)]
         ^{: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  :name)]
          [grid/cell {}
           [buttons/fa-icon {:event [::vendor-dialog/started v]
                             :icon "fa-pencil"}]]])]]]))
