(ns auto-ap.views.pages.transactions.table
  (:require [auto-ap.events :as events]
            [auto-ap.routes :as routes]
            [auto-ap.ssr-routes :as ssr-routes]
            [auto-ap.status :as status]
            [auto-ap.routes.payments :as payment-route]
            [auto-ap.subs :as subs]
            [auto-ap.views.components.buttons :as buttons]
            [auto-ap.views.components.dropdown
             :refer [drop-down drop-down-contents]]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.pages.data-page :as data-page]
            [auto-ap.views.pages.transactions.form :as edit]
            [auto-ap.views.utils
             :refer [action-cell-width date->str dispatch-event-with-propagation nf
                     pretty with-role]]
            [bidi.bidi :as bidi]
            [cemerick.url :as url]
            [re-frame.core :as re-frame]))

(re-frame/reg-event-fx
 ::editing-matches-found
 (fn [_ [_ which matches]]
   {:dispatch
    [::edit/editing which (:potential-payment-matches matches) (:potential-autopay-invoices-matches matches) (:potential-unpaid-invoices-matches matches) (:potential-transaction-rule-matches matches)]}))

(re-frame/reg-event-fx
 ::intend-to-edit
 [with-role]
 (fn [{:keys [db role]} [_ which]]
   {:graphql
    {:token (-> db :user)
     :owns-state {:multi ::edits
                  :which (:id which)}
     :query-obj {:venia/queries
                 (cond-> [{:query/data [:potential-payment-matches
                                        {:transaction_id (:id which)}
                                        [:id :memo :check-number [:vendor [:name]]]]}
                          {:query/data [:potential-payment-matches
                                        {:transaction_id (:id which)}
                                        [:id :memo :check-number [:vendor [:name]]]]}]
                   (or (= "admin" role)
                       (= "power-user" role))
                   
                   (into [{:query/data [:potential-autopay-invoices-matches
                                        {:transaction_id (:id which)}
                                        [:id :invoice-number :total :date :scheduled-payment [:vendor [:name]]]]}
                          {:query/data [:potential-unpaid-invoices-matches
                                        {:transaction_id (:id which)}
                                        [:id :invoice-number :total :date :scheduled-payment [:vendor [:name]]]]}])
                   (= "admin" role)
                   (into [{:query/data [:potential-transaction-rule-matches
                                        {:transaction_id (:id which)}
                                        [:id :note]]}]))}
     :on-success [::editing-matches-found which]}}))

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

(defn lock-icon []
  [:div {:style {:position "absolute" :width "1em" :height "1em" :left "-1.25rem"  :background-color "#E0E0E0" :padding "5px" :box-sizing "content-box" :border-radius "999px" :display "flex" :justify-content "center"  :align-content "center" :text-align "center"}}
   [:div
    [:i.fa.fa-lock {:style {:color "#333"}}]]])


(defn table [{:keys [data-page check-boxes? action-buttons]}]
  (let [selected-client @(re-frame/subscribe [::subs/client])
        {:keys [data params]} @(re-frame/subscribe [::data-page/page data-page])
        states @(re-frame/subscribe [::status/multi ::edits])]
    [grid/grid {:data-page data-page
                :column-count (if selected-client 6 7)
                :check-boxes? check-boxes?}
     [grid/controls (assoc data :action-buttons action-buttons)
      data]
     [grid/table {:fullwidth true}
      [grid/header {}
       [grid/row {:id  "header"
                  :entity params}
        (when-not selected-client
          [grid/sortable-header-cell {:sort-key "client" :sort-name "Client"} "Client"])
        [grid/sortable-header-cell {:sort-key "account" :sort-name "Bank Account"} "Bank Account"]
        [grid/sortable-header-cell {:sort-key "vendor" :sort-name "Vendor"} "Vendor"]
        [grid/sortable-header-cell {:sort-key "date" :sort-name "Date" :style {:width "8em"}} "Date"]
        [grid/sortable-header-cell {:sort-key "amount" :sort-name "Amount" :class "has-text-right" :style {:width "8em"}} "Amount"]
        [grid/sortable-header-cell {:sort-key "status" :sort-name "Status" :style {:width "7em"}} "Status"]
        [grid/header-cell {:style {:width (action-cell-width 3)}}]]]
      [grid/body
       (for [{:keys [client vendor payment expected-deposit status bank-account description-original date amount id yodlee-merchant] :as i} (:data data)]
         ^{:key id}
         [grid/row {:class (:class i) :id id :entity i}
          (when-not selected-client
            [grid/cell {:style {:overflow "visible" :position "relative" }}
             
             (when (:is-locked i)
               [lock-icon])
             (:name client)])
          #_[:td description-original]
          [grid/cell {}
          
           (when (and selected-client (:is-locked i))
             [lock-icon])
           (:name bank-account)]
          [grid/cell  {} [:<> (cond vendor
                                    (:name vendor)
                                    yodlee-merchant
                                    [:i.has-text-grey (str "Merchant '" (:name yodlee-merchant)  "'")]

                                    :else
                                    [:i.has-text-grey (str description-original)])
                          (when (:check-number  i)
                            [:div.tag.is-primary.is-light {:style {:margin-left "2em"}} "Check " (:check-number i)])]]
          [grid/cell {} (date->str date)]
          [grid/cell {:class "has-text-right"} (nf amount)]
          [grid/cell {} status]
          [grid/button-cell {}
           [:div.buttons
            [drop-down {:id [::expense-accounts id]
                        :header [buttons/sl-icon {:aria-haspopup true
                                                  :event [::events/toggle-menu [::expense-accounts id]]
                                                  :tab-index "0"
                                                  :icon "icon-saving-bank-1"}]}
             [drop-down-contents
              [:div
               [:span.dropdown-item description-original]]]]
            [buttons/fa-icon {:event [::intend-to-edit i]
                              :class (status/class-for (get states id))
                              :icon "fa-pencil"}]
            (when (some identity [payment expected-deposit])
              [drop-down {:id [::links id]
                          :is-right? true
                          :header [buttons/fa-icon {:class "badge"
                                                    :on-click (dispatch-event-with-propagation [::events/toggle-menu [::links id]])
                                                    :data-badge (str 1)
                                                    :icon "fa-paperclip"}]}
               [drop-down-contents
                [:div.dropdown-item
                 [:table.table.grid.compact
                  [:tbody
                   (when payment
                     [:tr
                      [:td
                       "Payment"]
                      [:td (date->str (:date payment) pretty)]
                      [:td
                       [buttons/fa-icon {:icon "fa-external-link"
                                         :href (str (bidi/path-for ssr-routes/only-routes ::payment-route/all-page)
                                                    "?"
                                                    (url/map->query {:exact-match-id (:id payment)}))}]]])
                   (when expected-deposit
                     [:tr
                      [:td
                       "Expected Deposit"]
                      [:td (date->str (:date expected-deposit) pretty)]
                      [:td
                       [buttons/fa-icon {:icon "fa-external-link"
                                         :href (str (bidi/path-for routes/routes :expected-deposits)
                                                    "?"
                                                    (url/map->query {:exact-match-id (:id expected-deposit)}))}]]])]]]]])]]])]]
     [grid/bottom-paginator data]]))
