(ns auto-ap.views.pages.reports.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.pages.data-page :as data-page]
   [auto-ap.views.utils :refer [action-cell-width date->str dispatch-event]]
   [re-frame.core :as re-frame]))

(re-frame/reg-event-fx
  ::delete-report
  (fn [{:keys [db]} [_ {id :id data-page :data-page}]]
    {:graphql
     {:token      (-> db :user)
      :owns-state {:single ::delete}
      :query-obj  {:venia/operation {:operation/type :mutation
                                     :operation/name "DeleteReport"}
                   :venia/queries   [{:query/data [:delete-report
                                                   {:id id}
                                                   [:message]]}]}  
      :on-success (fn [_]
                    [::data-page/updated-entity data-page {:name "deleted"
                                                           :id id}]
                    #_[::invoice-updated ()(:void-invoice result)])}}))

(defn row [{{:keys [name creator created url id] :as i} :row is-admin? :is-admin? data-page :data-page}]
  [:<>
   [grid/row {:class (:class i) :id id}
    [grid/cell {} name]
    [grid/cell {} creator]
    [grid/cell {} (date->str created) ]
    [grid/button-cell {}
     [:div.buttons 
      (when (not= "deleted" name)
        [buttons/fa-icon {:icon "fa-external-link"
                          :href url}])
      (when (not= "deleted" name)
        (when is-admin? 
          [buttons/fa-icon {:icon     "fa-trash"
                            :on-click (dispatch-event [::delete-report {:id id :data-page data-page}])}]))]]]])

(defn table [{:keys [data-page]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])
        is-admin? @(re-frame/subscribe [::subs/is-admin?])]
    [:div
     [status/status-notification {:statuses [[::status/single ::delete]]}]
     [grid/grid {:data-page    data-page
                 :column-count 3}
      [grid/controls data]
      [grid/table {:fullwidth true :class ["wrappable"]}
       [grid/header 
        [grid/row {}
         [grid/sortable-header-cell {:sort-key "name" :sort-name "Name"} "Name"]
         [grid/sortable-header-cell {:sort-key "creator" :sort-name "Created by"} "Created by"]
         [grid/sortable-header-cell {:sort-key "created" :sort-name "Created" :style {:width "8em"}} "Created"]
         [grid/header-cell {:style {:width (action-cell-width (if 
                                                                  is-admin?
                                                                2
                                                                1))}}]
         ]]
       [grid/body
        (for [i (:data data)]
          ^{:key (:id i)}
          [row {:row i :is-admin? is-admin? :data-page data-page}])]]]]))

