(ns auto-ap.views.pages.admin.rules.table
  (:require
   [auto-ap.status :as status]
   [auto-ap.subs :as subs]
   [auto-ap.views.components.buttons :as buttons]
   [auto-ap.views.components.grid :as grid]
   [auto-ap.views.components.modal :as modal]
   [auto-ap.views.pages.admin.rules.form :as form]
   [auto-ap.views.pages.admin.rules.results-modal :as results-modal]
   [auto-ap.views.pages.data-page :as data-page]
   [auto-ap.views.utils
    :refer [->$ action-cell-width dispatch-event with-user]]
   [re-frame.core :as re-frame]
   [reagent.core :as r]))

(re-frame/reg-event-fx
 ::run-clicked
 [with-user]
 (fn [{:keys [user]} [_ which]]
   {:graphql
    {:token user
     :owns-state {:multi ::run
                  :which (:id which)}
     :query-obj {:venia/operation {:operation/type :query
                                   :operation/name "RunTransactionRule"}
                 :venia/queries [{:query/data [:run-transaction-rule
                                               {:transaction-rule-id (:id which)}
                                               [:id
                                                :date
                                                :amount
                                                [:client [:name]]
                                                [:bank-account [:name]]
                                                :description-original]]}]}
     :on-success [::succeeded-run (:id which)]}}))


(re-frame/reg-event-fx
 ::succeeded-run
 (fn [_ [_ transaction-rule-id result]]
   {:dispatch [::results-modal/opening (:run-transaction-rule result) transaction-rule-id true]}))

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

(re-frame/reg-event-db
 ::unmounted
 (fn [db]
   (status/reset-multi db ::run)))

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

(re-frame/reg-event-fx
 ::deleted-transaction-rule
 (fn []
   {:dispatch [::modal/modal-closed]}))

(re-frame/reg-event-fx
 ::delete-transaction-rule
 [with-user]
 (fn [{:keys [user]} [_ id]]
   {:graphql
    {:token user
     :owns-state {:single ::delete-transaction-rule}
     :query-obj {:venia/operation {:operation/type :mutation
                                   :operation/name "DeleteTransactionRule"}
                 :venia/queries [{:query/data [:delete-transaction-rule
                                               {:transaction-rule-id id}]}]}
     :on-success [::deleted-transaction-rule]}}))


;; TODO  count how many transactions
(re-frame/reg-event-fx
 ::request-delete
 (fn [_ [_ which]]
   {:dispatch [::modal/modal-requested {:title "Confirmation"
                                        :body [:div "Are you sure you want to delete transaction rule '" (:description which) "'? Any previously transactions will remain updated, but the rule association will be lost."]
                                        :cancel? true
                                        :confirm {:value "Delete Transaction Rule"
                                                  :class "is-danger"
                                                  :status-from [::status/single ::delete-transaction-rule]
                                                  :on-click (dispatch-event [::delete-transaction-rule (:id which)] )}
                                        :close-event [::status/completed ::delete-transaction-rule]}]}))



(defn table* [{:keys [data-page]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])
        _ @(re-frame/subscribe [::subs/client])
        states @(re-frame/subscribe [::status/multi ::run])]
    [grid/grid {:data-page data-page
                :column-count 6}
     [grid/controls data]
     [grid/table {:fullwidth true }
      [grid/header
       [grid/row {}
        [grid/sortable-header-cell {:sort-key "client"
                                    :sort-name "Client"}
         "Client"]

        [grid/sortable-header-cell {:sort-key "bank-account"
                                    :sort-name "Bank Account"}
         "Bank Account"]

        [grid/sortable-header-cell {:sort-key "description"
                                    :sort-name "Description"}
         "Description"]

        [grid/header-cell {:style {:width "12em"}} "Amount"]

        [grid/sortable-header-cell {:sort-key "note"
                                    :sort-name "Note"}
         "Note"]

        [grid/header-cell {:style {:width (action-cell-width 3)}}]]]
      [grid/body
       (for [{:keys [client bank-account description amount-lte amount-gte note id] :as r} (:data data)]
         ^{:key id}
         [grid/row {:class (:class r) :id id}
          [grid/cell {} (:name client)]
          [grid/cell {} (:name bank-account)]
          [grid/cell {} description]
          [grid/cell {:class "has-text-right"}
           (cond (and amount-gte amount-lte)
                 (str (->$ amount-gte) " - " (->$ amount-lte))

                 amount-gte
                 (str ">=" (->$ amount-gte))

                 amount-lte
                 (str "<=" (->$ amount-lte))

                 :else
                 "")]
          [grid/cell {} note]
          [grid/cell {} 
           [:div.buttons 
            [buttons/fa-icon {:event [::run-clicked r] :icon :fa-play :class (status/class-for (get states (:id r)))}]
            [buttons/sl-icon {:event [::request-delete r] :icon :icon-bin-2}]
            [buttons/fa-icon {:event [::form/editing r] :icon :fa-pencil}]]]])]]]))

(defn table []
  (r/create-class {:component-will-unmount (dispatch-event [::unmounted])
                   :reagent-render (fn [params]
                                     [table* params])}))
