(ns auto-ap.views.pages.payments.table
  (:require [auto-ap.events :as events]
            [auto-ap.routes :as routes]
            [auto-ap.status :as status]
            [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.utils
             :refer
             [date->str dispatch-event-with-propagation nf pretty]]
            [bidi.bidi :as bidi]
            [cemerick.url :as url]
            [goog.string :as gstring]
            [re-frame.core :as re-frame]))

(re-frame/reg-event-fx
 ::void-check
 (fn [{:keys [db]} [_ payment]]
   {:graphql
    {:token (-> db :user)
     :owns-state {:multi ::void
                  :which (:id payment)}
     :query-obj {:venia/operation {:operation/type :mutation
                                   :operation/name "VoidPayment"}
                 :venia/queries [{:query/data [:void-payment
                                               {:payment-id (:id payment)}
                                               [:id :status [:bank-account [:name]] :amount :check_number :s3_url :date [:vendor [:name :id]] [:client [:name :id]]
                                                [:invoices [:invoice-id]]]]}]}  
     :on-success [::payment-voided]}}))

(re-frame/reg-event-db
 ::payment-voided
 (fn [db [_ _]]
   db))

(defn row [{check :check 
            selected-client :selected-client
            states :states
            }]
  (let [{:keys [client s3-url bank-account type check-number date amount id vendor status invoices transaction] :as check} check]
    [grid/row {:class (:class check) :id id :entity check}
     (when-not selected-client
       [grid/cell {} (:name client)])
     [grid/cell {} (:name vendor)]
     [grid/cell {} (:name bank-account)]
     [grid/cell {} (cond
            (= :cash type) "Cash"
            (= :debit type) "Debit"
            :else (if s3-url
                    [:a.button {:href s3-url :target "_new"} [:span [:span.icon [:i.fa.fa-share-square-o]]
                                                       [:span (str  " " check-number )]]]
                    check-number))]
     [grid/cell {} (date->str date) ]
     [grid/cell {:class "has-text-right"} (nf amount )]
     [grid/cell {} status]
     [grid/button-cell {}
      [:div.buttons 
       (when (and (seq invoices) (not= :voided status))
         [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 (cond-> (clojure.core/count invoices)
                                                                  transaction inc))
                                               :icon "fa-paperclip"}]}
          [drop-down-contents
           [:div.dropdown-item 
            [:table.table.grid.compact
             [:tbody 
              (for [invoice invoices]
                ^{:key (:id invoice)}
                [:tr
                 [:td
                  "Invoice " (:invoice-number (:invoice invoice))
                  ]
                 [:td (gstring/format "$%.2f" (:amount invoice) )]
                 [:td 
                  [buttons/fa-icon {:icon "fa-external-link"
                                    :href (str (bidi/path-for routes/routes :invoices )
                                               "?"
                                               (url/map->query {:exact-match-id (:id (:invoice invoice))}))}]]])
              (when transaction
                [:tr
                 [:td
                  "Transaction"]
                 [:td (date->str (:date transaction) pretty)]
                 [:td 
                  [buttons/fa-icon {:icon "fa-external-link"
                                    :href (str (bidi/path-for routes/routes :transactions )
                                               "?"
                                               (url/map->query {:exact-match-id (:id transaction)}))}]]])]]]]])
       [:span {:style {:margin-left "1em"}}]

       (when (and (or (not= :cleared status)
                      (= :balance-credit type))
                  (not= :voided status)
                  (not transaction))
           
         [buttons/sl-icon {:event [::void-check check] :icon :icon-bin-2
                           :class (status/class-for (get states (:id check)))}])]]]))

(defn table [{:keys [data-page 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 ::void])]
    [grid/grid {:data-page data-page
                :check-boxes? true
                :column-count (if selected-client 7 8)}
     [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 "vendor" :sort-name "Vendor"} "Vendor"]
        [grid/sortable-header-cell {:sort-key "bank-account" :sort-name "Bank Account"} "Bank Account"]
        [grid/sortable-header-cell {:sort-key "check-number" :sort-name "Check Number"} "Check Number"]
        [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 "12em"}}]]]
      [grid/body
       (for [check (:data data)]
         ^{:key (:id check)}
         [row {:check check
               :selected-client selected-client
               :states states}])]]]))
