(ns auto-ap.views.pages.admin.reminders
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [re-frame.core :as re-frame]
            [auto-ap.views.components.paginator :refer [paginator]]
            [auto-ap.views.components.sorter :refer [sorted-column]]
            [auto-ap.entities.vendors :as entity]
            [reagent.core :as reagent]
            [auto-ap.subs :as subs]
            [auto-ap.views.utils :refer [login-url dispatch-value-change dispatch-event date-time->str date->str horizontal-field bind-field]]
            [cljs.reader :as edn]
            
            [auto-ap.routes :as routes]
            [bidi.bidi :as bidi]))
(re-frame/reg-sub
 ::editing-reminder
 (fn [db]
   (::editing-reminder db)))

(re-frame/reg-sub
 ::reminder-page
 (fn [db]
   (::reminder-page db)))

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

(re-frame/reg-event-db
 ::edit
 (fn  [db [_ which]]
   (assoc db ::editing-reminder which)))

(re-frame/reg-event-db
 ::change
 (fn  [db [_ field v]]
   (assoc-in db (into [::editing-reminder]  field) v)))

(re-frame/reg-event-fx
 ::mounted
 (fn  [{:keys [db]} _]
   {:db (assoc db ::reminder-params {:start 0})
    :dispatch [::invalidated]}))

(re-frame/reg-event-fx
 ::params-changed
 (fn  [{:keys [db]} [_ params]]
   {:db (update db ::reminder-params merge params)
    :dispatch [::invalidated]}))

(re-frame/reg-event-fx
 ::save
 (fn [{:keys [db]}]
   (let [edited-reminder (::editing-reminder db)]
     (println edited-reminder)
     {:http {:token (:user db)
             :method :put 
             :body (pr-str (dissoc edited-reminder :sent :scheduled))
             :headers {"Content-Type" "application/edn"}
             :uri (str "/api/reminders/" (:id edited-reminder))
             :on-success [::save-complete]
             :on-error [::save-error]}})))

(re-frame/reg-event-fx
 ::save-complete
 (fn [{:keys [db]}]
   {:dispatch [::edit nil]}))

(re-frame/reg-event-fx
 ::save-error
 (fn [{:keys [db]}]
   {:dispatch [::change [:error] true]}))

(re-frame/reg-event-fx
 ::invalidated
 (fn [{:keys [db]}]
   {:graphql {:token (:user db)
              :query-obj {:venia/queries [[:reminder_page
                                           (::reminder-params db)
                                           
                                           [[:reminders [:id :email :sent :scheduled :subject :body [:vendor [:name :id]] ]]
                                            :total
                                            :start
                                            :end]]]}
              
              :on-success [::received]}}))


(re-frame/reg-event-db
 ::received
 (fn [db [_ reminders]]
   (assoc db ::reminder-page (first (:reminder-page reminders)))))

(defn edit-dialog []
  (let [editing-reminder @(re-frame/subscribe [::editing-reminder])]
    [:div.modal.is-active
     [:div.modal-background {:on-click (fn [] (re-frame/dispatch [::edit nil]))}]
     
     [:div.modal-card
      [:header.modal-card-head
       [:p.modal-card-title
        (str "Reminder for " (:name (:vendor editing-reminder)))]
       (when (:error editing-reminder)
         [:span.icon.has-text-danger
          [:i.fa.fa-exclamation-triangle]])
       [:button.delete {:on-click (fn [] (re-frame/dispatch [::edit nil]))}]]
      [:section.modal-card-body
       [horizontal-field
        [:label.label "Email"]
        [:div.control
         [bind-field
          [:input.input {:type "text"
                         :field :email
                         :event ::change
                         :subscription editing-reminder}]]]]
      [horizontal-field
        [:label.label "Subject"]
        [:div.control
         [bind-field
          [:input.input {:type "text"
                         :field :subject
                         :event ::change
                         :subscription editing-reminder}]]]] 
       
       [horizontal-field
        [:label.label "Body"]
        [:div.control

         [bind-field
          [:textarea.textarea.is-expanded {:type "text"
                                           :field :body
                                           :event ::change
                                           :subscription editing-reminder}]]]] 
       
       (when (:saving? editing-reminder) [:div.is-overlay {:style {"backgroundColor" "rgba(150,150,150, 0.5)"}}])]
      
      [:footer.modal-card-foot
       [:button.button.is-primary {:on-click (fn [] (re-frame/dispatch [::save]))
                                   #_#_:disabled (when (not (s/valid? ::entity/vendor editing-reminder ))
                                               "disabled")}
        [:span "Save"] 
        (when (:saving? editing-reminder)
          [:span.icon
           [:i.fa.fa-spin.fa-spinner]])]]]]))

(defn reminders-table []
  (let [{:keys [reminders start end total count]} @(re-frame/subscribe [::reminder-page])
        {:keys [sort-by asc]} @(re-frame/subscribe [::reminder-params])
        reminders (or reminders [])]
    [:div
     [:div.is-pulled-right
      [paginator {:start start
                  :end end
                  :total total
                  :count count
                  :on-change (fn [params]
                               (re-frame/dispatch [::params-changed params]))}]]
     [:table {:class "table", :style {:width "100%"}}
      [:thead  
       [:tr  
        (for [[sort-key name] [["vendor" "Vendor"]
                               ["scheduled" "Scheduled Date"]
                               ["sent" "Status"]
                               ["email" "Email"]]]
          ^{:key name}
          [sorted-column {:on-sort (fn [params] (re-frame/dispatch [::params-changed params]))
                          :style {:width "20%" :cursor "pointer"}
                          :sort-key sort-key 
                          :sort-by sort-by
                          :asc asc}
           name])]]
      [:tbody (for [{:keys [id vendor scheduled sent email ] :as r} reminders]
                ^{:key id}
                [:tr  (when-not sent
                          {:on-click (fn [] (re-frame/dispatch [::edit r])) :style {:cursor "pointer"}})
                 [:td (:name vendor)]
                 [:td (date->str scheduled)]
                 [:td (when sent
                        [:span [:span.icon [:i.fa.fa-check]] "Sent " (date-time->str sent)]) ]
                 [:td email]])]]

     (when @(re-frame/subscribe [::editing-reminder])
       [edit-dialog])]))


(defn admin-reminders-page []
  [(with-meta
     (fn []
       [:div
        [:h1.title "Reminders"]
        [reminders-table]])
     {:component-did-mount (fn []
                             (re-frame/dispatch [::mounted]))})])
