(ns auto-ap.views.pages.ledger.table
  (:require [auto-ap.events :as events]
            [auto-ap.routes :as routes]
            [auto-ap.ssr-routes :as ssr-routes]
            [auto-ap.routes.invoice :as i-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]
            [clojure.string :as str]
            [auto-ap.views.utils
             :refer
             [date->str dispatch-event-with-propagation nf action-cell-width]]
            [bidi.bidi :as bidi]
            [cemerick.url :as url]
            [re-frame.core :as re-frame]))

(defn ledger-row [{{:keys [client vendor alternate-description note date amount id line-items source original-entity] :as i} :row
                   :keys [selected-client bank-accounts-by-id]}]
  [:<>
   [grid/row {:class (:class i) :id id}
    (when-not selected-client
      [grid/cell {} (:name client)])
    [grid/cell {} (cond
                    (and (= "Imported Entry" (:name vendor)) (not (str/blank? note)))
                    note

                    vendor
                    (:name vendor)

                    :else
                    [:i.has-text-grey (or (when alternate-description (str "Bank Description: " alternate-description))
                                          "Unknown Merchant")])]
    [grid/cell {} (date->str date) ]
    [grid/cell {} ]
    [grid/cell {:class "has-text-right"} (nf amount )]
    [grid/cell {:class "has-text-right"} (nf amount )]
    [grid/button-cell {}
        (when (#{"invoice" "transaction"} source)
          [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 
               (cond
                 (= "invoice" source)
                 [:tr
                  [:td
                   "Invoice"]
                  [:td 
                   [buttons/fa-icon {:icon "fa-external-link"
                                     :href (str (bidi/path-for ssr-routes/only-routes ::i-route/all-page )
                                                "?"
                                                (url/map->query {:exact-match-id original-entity}))}]]]
                 (= "transaction" source)
                 [:tr
                  [:td
                   "Transaction"]
                  [:td 
                   [buttons/fa-icon {:icon "fa-external-link"
                                     :href (str (bidi/path-for routes/routes :transactions )
                                                "?"
                                                (url/map->query {:exact-match-id original-entity}))}]]]

                 :else
                 nil
                 )]]]]])]]
   [:<>
    (for [{:keys [debit credit location account id running-balance]} line-items
          :let [account (or (bank-accounts-by-id (:id account))
                            account)]]
      ^{:key id}
      [grid/row {}
       (when-not selected-client
         [grid/cell {} ])
       [grid/cell {} ]
       [grid/cell {} ]
       [grid/cell {} (if (:name account)
                       [:span.has-tooltip-arrow.has-tooltip-right {:data-tooltip (str "Balance as of this entry: " (nf running-balance ))}
                        (str location ": " (:name account)) ]
                       [:i "unknown"])]
       [grid/cell {:class "has-text-right"} (when debit (nf debit ))]
       [grid/cell {:class "has-text-right"} (when credit (nf credit ))]
       [grid/button-cell {}
        ]

       #_[grid/cell {:class "has-text-right"} (when running-balance (nf running-balance ))]])]])

(defn table [{:keys [data-page action-buttons]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])
        selected-client @(re-frame/subscribe [::subs/client])
        bank-accounts-by-id @(re-frame/subscribe [::subs/bank-accounts-by-id])]
    [grid/grid {:data-page data-page
                :column-count (if selected-client 5 6)}
     [grid/controls (assoc data :action-buttons action-buttons)]
     [grid/table {:fullwidth true :class ["wrappable"]}
      [grid/header
       [grid/row {}
        (when-not selected-client
          [grid/sortable-header-cell {:sort-key "client" :sort-name "Client"} "Client"])
        [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/header-cell {} "Account"]
        [grid/sortable-header-cell {:sort-key "amount" :sort-name "Amount" :class "has-text-right" :style {:width "7em"}} "Debit"]
        [grid/sortable-header-cell {:sort-key "amount" :sort-name "Amount" :class "has-text-right" :style {:width "7em"}} "Credit"]
        [grid/header-cell {:style {:width (action-cell-width 1)}}]
        #_[grid/header-cell {:class "has-text-right" :style {:width "10em"}} "Running Balance"]]]
      [grid/body
       (for [{:keys [id] :as i} (:data data)]
         ^{:key id}
         [ledger-row {:row i
                      :selected-client selected-client
                      :bank-accounts-by-id bank-accounts-by-id}])]]
     [grid/bottom-paginator data]
     #_[grid/controls (assoc data :action-buttons action-buttons)]]))

