(ns auto-ap.views.pages.invoices.advanced-print-checks
  (:require [auto-ap.forms :as forms]
            [auto-ap.status :as status]
            [auto-ap.subs :as subs]
            [auto-ap.utils :refer [by]]
            [auto-ap.views.components.modal :as modal]
            [auto-ap.views.pages.invoices.common :refer [invoice-read does-amount-exceed-outstanding?]]
            [auto-ap.views.pages.invoices.form :as form]
            [auto-ap.views.utils :refer [dispatch-event horizontal-field with-user]]
            [re-frame.core :as re-frame]))

(re-frame/reg-sub
 ::can-submit
 :<- [::forms/form ::form]
 (fn [{ {:keys [invoices invoice-amounts]} :data}]
   (cond (seq (filter
               (fn [{:keys [id outstanding-balance]}]
                 (does-amount-exceed-outstanding? (get-in invoice-amounts [id :amount]) outstanding-balance ))
               invoices))
         false

         :else
         true)))

(def advanced-print-checks-form (forms/vertical-form {:submit-event [::save]
                                                      :change-event [::forms/change ::form]
                                                      :can-submit [::can-submit]
                                                      :id ::form}))


(defn form []
  (let [real-bank-accounts @(re-frame/subscribe [::subs/real-bank-accounts])
        {:keys [data active? error id]} @(re-frame/subscribe [::forms/form ::form])
        {:keys [form-inline horizontal-field field raw-field error-notification submit-button]} advanced-print-checks-form]

    (form-inline {}
                 [:<>
                  [:div.field
                   [:label.label  "Pay using"]
                   [:div.control 
                    [:span.select
                     [raw-field
                      [:select {:type "select"
                                :field :bank-account-id}
                       (for [{:keys [id number name]} real-bank-accounts]
                         ^{:key id} [:option {:value id} name])]]]]]

                  [:table.table.is-fullwidth
                   [:thead
                    [:tr
                     [:th "Vendor"]
                     [:th "Invoice ID"]
                     [:th {:style {"width" "10em"}} "Payment"]]]
                   [:tbody
                    (doall
                     (for [{:keys [vendor payment outstanding-balance invoice-number id] :as i} (:invoices data)]
                       ^{:key id}
                       [:tr
                        [:td (:name vendor)]
                        [:td invoice-number]
                        
                        [:td  [:div.field.has-addons.is-extended
                               [:p.control [:a.button.is-static "$"]]
                               [:p.control
                                (raw-field 
                                 [:input.input.has-text-right {:type "number"
                                                               :field [:invoice-amounts id :amount]
                                                               :step "0.01"}])]]]]))]]])))

(re-frame/reg-event-fx
 ::show
 (fn [{:keys [db]} [_ invoices]]
   {:dispatch [::modal/modal-requested {:title "Print Checks"
                                        :body [form]
                                        :confirm {:value "Print checks"
                                                  :status-from [::status/single ::form]
                                                  :class "is-primary"
                                                  :on-click (dispatch-event [::save])
                                                  :can-submit [::can-submit]
                                                  :close-event [::status/completed ::form]}}]
    :db (-> db
            (forms/start-form ::form
                              {:bank-account-id (:id (first @(re-frame/subscribe [::subs/real-bank-accounts])))
                               :invoices invoices
                               :invoice-amounts (into {}
                                                      (map (fn [i] [(:id i)
                                                                    {:amount (:outstanding-balance i)}])
                                                           invoices))}))}))



(re-frame/reg-event-fx
 ::save
 [with-user (forms/in-form ::form) ]
 (fn [{:keys [db user]} [_ bank-account-id]]
   (let [type (or (->> @(re-frame/subscribe [::subs/client])
                       :bank-accounts
                       (filter #(= bank-account-id (:id %)))
                       first
                       :type)
                  :check)
         {:keys [date invoices invoice-amounts check-number bank-account-id client]} (:data db)]
     {:graphql
      {:token user
       :owns-state {:single ::form}
       :query-obj {:venia/operation {:operation/type :mutation
                                     :operation/name "PrintChecks"}
                   
                   :venia/queries [[:print-checks
                                    {:invoice_payments (map (fn [x]
                                                              {:invoice-id (:id x)
                                                               :amount (get-in invoice-amounts [(:id x) :amount])})
                                                            invoices)
                                     :type type
                                     :bank_account_id bank-account-id
                                     :client_id (->> invoices first :client :id)}
                                    [[:invoices invoice-read]
                                     :pdf_url]]]}
       :on-success (fn [result]
                     [::checks-printed
                      (:invoices (:print-checks result))
                      (:pdf-url (:print-checks result))])}})))

(re-frame/reg-event-fx
 ::checks-printed
 (fn [{:keys [db]} [_ data]]
   {:dispatch [::modal/modal-closed]}))

