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

(re-frame/reg-event-fx
 ::run-clicked
 [with-user]
 (fn [{:keys [user db]} [_ 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 [{:keys [db]} [_ 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
 ::params-changed
 [(re-frame/path [::table-params])]
 (fn [{table-params :db} [_ params :as z]]
   {:db (merge table-params 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 [db 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 [id data-page]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])
        selected-client @(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 [params]
  (r/create-class {:component-will-unmount (dispatch-event [::unmounted])
                   :reagent-render (fn [params]
                                     [table* params])}))
