(ns auto-ap.views.pages.import-invoices
  (:require [re-frame.core :as re-frame]
            [reagent.core :as reagent]
            [auto-ap.events :as events]
            [auto-ap.subs :as subs]
            [auto-ap.entities.companies :as company]
            [auto-ap.entities.vendors :as vendor]
            [auto-ap.views.components.invoice-table :refer [invoice-table] :as invoice-table]
            [cljsjs.dropzone :as dropzone]
            [cljs.reader :as edn]))
(def dropzone
  (let [company (re-frame/subscribe [::subs/company])
        token (re-frame/subscribe [::subs/token])]
    (with-meta
      (fn []
        [:form.dz {:action "/api/invoices/upload"}
         [:div.tile.notification
          [:div.has-text-centered {:style {:padding "80px 0px" :width "100%"}}
           [:span
            [:span {:class "icon"}
             [:i {:class "fa fa-cloud-download"}]]
            "Drop any invoices you want to process here"]]]])
      {:component-did-mount (fn [this]
                              (js/Dropzone. (reagent/dom-node this)
                                            (clj->js {:init (fn []
                                                              (.on (js-this) "success" (fn [_ files]
                                                                                         (re-frame/dispatch [::invalidated]))))
                                                      :paramName "file"
                                                      :headers {"Authorization" (str "Token " @token)}
                                                      :url (str "/api/invoices/upload"
                                                                (when-let [company-name (-> @company :id)]
                                                                  (str "?company=" company-name)))
                                                      :previewsContainer "#dz-hidden"
                                                      :previewTemplate "<div class='dz-hidden-preview'></div>"})))})))

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

(re-frame/reg-sub
 ::params
 (fn [db]
   (-> db (::params {}))))

(re-frame/reg-event-fx
 ::invalidated
 (fn [cofx [_ params]]
   {:dispatch [::params-change @(re-frame/subscribe [::params])]}))

(re-frame/reg-event-fx
 ::params-change
 (fn [cofx [_ params]]
   
   {:db (-> (:db cofx)
            (assoc-in  [:status :loading] true)
            (assoc-in [::params] params))
    :graphql {:token (-> cofx :db :user)
              :query-obj (invoice-table/query (assoc params :imported false)) 
              :on-success [::received]}}))

(re-frame/reg-event-db
 ::received
 (fn [db [_ data]]
   (-> db
       (assoc ::invoice-page (first (:invoice-page data)))
       (assoc-in [:status :loading] false))))

(re-frame/reg-event-fx
 ::reject-invoices
 (fn  [cofx [_ on-success]]
   {:http {:method :post
           :token (-> cofx :db :user)
           :uri (str "/api/invoices/reject"
                     (when-let [company-id (:id @(re-frame/subscribe [::subs/company]))]
                       (str "?company=" company-id)))
           :on-success on-success
           }}))

(re-frame/reg-event-fx
 ::approve-invoices
 (fn  [cofx [_ on-success]]
   {:http {:method :post
           :token (-> cofx :db :user)
           :uri (str "/api/invoices/approve"
                     (when-let [company-id (:id @(re-frame/subscribe [::subs/company]))]
                       (str "?company=" company-id)))
           :on-success on-success
           }}))

(def import-invoices-page
  (with-meta
    (fn []
      (let [invoice-page (re-frame/subscribe [::invoice-page])
            status (re-frame/subscribe [::subs/status])]
        [:div
         [:h1.title "Upload invoices"]
         [dropzone]
         
         [:div {:class "section"}]
         [:div {:class "card found-invoices",}
          [:div {:class "card-header"}
           [:span {:class "card-header-title"} "Found Invoices"]]
          [:div {:class "card-content"}
           (if (:loading @status)
             [:h1.title
              [:i.fa.fa-spin.fa-spinner]]
             (if (seq (:invoices @invoice-page))
               [invoice-table {:id :approved
                               :invoice-page  invoice-page
                               :status (re-frame/subscribe [::subs/status])
                               :params (re-frame/subscribe [::params])
                               :on-params-change (fn [params]
                                                   (re-frame/dispatch [::params-change params])) }]
               [:span "No pending invoices"]))]
          (if (and (seq (:invoices @invoice-page)) (not (:loading @status)))
            [:div.card-footer
             [:a.card-footer-item
              {:on-click (fn [e]
                           (.preventDefault e)
                           (re-frame/dispatch [::approve-invoices
                                               [::invalidated]]))}
              "Accept all"]
             [:a.card-footer-item
              {:on-click (fn [e]
                           (.preventDefault e)
                           (re-frame/dispatch [::reject-invoices
                                               [::invalidated]]))}
              "Reject all"]])]]))
    {:component-will-mount (fn []
                             (re-frame/dispatch-sync [::invalidated]))}))
