(ns auto-ap.views.pages.admin.clients.table
  (:require [auto-ap.subs :as subs]
            [clojure.string :as str]
            [re-frame.core :as re-frame]
            [auto-ap.views.utils :refer [action-cell-width date->str with-user]]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.components.modal :as modal]
            [auto-ap.views.components.buttons :as buttons]
            [auto-ap.status :as status]
            [bidi.bidi :as bidi]
            [auto-ap.routes :as routes]))

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

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

(re-frame/reg-event-fx
  ::sales-queries-setup
  (fn [_ [_ results]]
    {:dispatch [::modal/modal-requested {:title "Sales Queries"
                                         :body  [:div [:pre (:message (:setup-sales-queries results))]]}]}))

(re-frame/reg-event-fx
  ::setup-sales-queries
  [with-user]
  (fn [{:keys [user]} [_ client-id]]
    {:graphql
     {:token      user
      :owns-state {:multi ::setup-sales-queries
                   :which client-id}
      :query-obj  {:venia/operation {:operation/type :mutation
                                     :operation/name "SetupSalesQueries"}
                   :venia/queries   [{:query/data [:setup-sales-queries
                                                   {:client-id client-id}
                                                   [:message]]}]}
      :on-success [::sales-queries-setup]}}
    ))

(re-frame/reg-sub
 ::params
 :<- [::specific-params]
 :<- [::subs/query-params]
 (fn [[specific-params query-params]]
   (merge (select-keys query-params #{:start :sort}) specific-params )))


(defn integration-status-badge [name status]
  (condp = (:state status)
    :success
    [:div.tag.has-tooltip-right.has-tooltip-arrow {:data-tooltip (str "Last updated:" (date->str (:last-updated status))
                                                                      "\n"
                                                                      "Last Attempted:" (date->str (:last-attempt status)))} [:span.icon [:i.has-text-success.fa.fa-check]]  [:span name]]

    :failed
    [:div.tag.is-danger.is-light.has-tooltip-right.has-tooltip-arrow {:data-tooltip (str "Last updated:" (date->str (:last-updated status))
                                                                                 "\n"
                                                                                 "Last Attempted:" (date->str (:last-attempt status))
                                                                                 "\n"
                                                                                 (:message status))
                                                              } [:span.icon [:i.has-text-danger.fa.fa-warning]]  [:span name]]

    :unauthorized
    [:div.tag.is-danger.is-light.has-tooltip-right.has-tooltip-arrow {:data-tooltip (str "Last updated:" (date->str (:last-updated status))
                                                                                         "\n"
                                                                                         "Last Attempted:" (date->str (:last-attempt status))
                                                                                         "\n"
                                                                                         "Your user is unauthorized. Detail:\n"
                                                                                         (:message status))
                                                                      } [:span.icon [:i.has-text-danger.fa.fa-warning]]  [:span name]]
    nil
    ))

(defn clients-table [{:keys [page status]}]
  (let [states @(re-frame/subscribe [::status/multi ::setup-sales-queries])]
    [grid/grid {:on-params-change (fn [p]
                                    (re-frame/dispatch [::params-changed p]))
                :status           status
                :params           @(re-frame/subscribe [::params])
                :column-count     5}
     [grid/controls page]
     [grid/table {:fullwidth true}
      [grid/header 
       [grid/row {}
        [grid/header-cell {} "Name"]
        [grid/header-cell {:style {:width "20em"}} "Code"]
        [grid/header-cell {} "Locations"]
        [grid/header-cell {} "Status"]
        [grid/header-cell {} "Email"]
        [grid/header-cell {:style {:width (action-cell-width 2)}}]]
       ]
      [grid/body
       (for [{:keys [id name email square-integration-status locked-until code locations bank-accounts]} (:data page)]
         ^{:key (str name "-" id )}
         [grid/row {:id id}
          [grid/cell {} name]
          [grid/cell {} code]
          [grid/cell {} (str/join ", " locations)]
          [grid/cell {:class "expandable"} [:div.tags
                         
                         [:div.tag (or (some-> locked-until date->str (#(str "Locked " %))) "Not locked")]
                         [integration-status-badge "Square" square-integration-status]
                         [:<> 
                          (for [bank-account bank-accounts
                                :let [code (:code bank-account)
                                      integration-status (:integration-status bank-account)]
                                :when (:id integration-status)]
                            ^{:key (:id integration-status)}
                            [integration-status-badge code integration-status])]]]
          [grid/cell {} email]
          [grid/cell {} [:div.buttons [buttons/fa-icon {:event [::setup-sales-queries id]
                                                        :class (status/class-for (get states id))
                                                        :icon  :fa-dollar}]
                         [buttons/fa-icon {:href (bidi/path-for routes/routes :admin-specific-client :id id)
                                           :icon :fa-pencil}]]]])]]]))
