(ns auto-ap.views.pages.admin.clients
  (:require [re-frame.core :as re-frame]
            [reagent.core :as reagent]
            [clojure.spec.alpha :as s]
            [clojure.string :as str]
            [cljs-time.core :as t]
            [cljs-time.coerce :as coerce]
            [auto-ap.subs :as subs]
            [auto-ap.forms :as forms]
            [auto-ap.events :as events]
            [auto-ap.entities.clients :as entity]
            [auto-ap.views.components.address :refer [address-field]]
            [auto-ap.views.components.layouts :refer [side-bar-layout appearing-side-bar side-bar] ]
            [auto-ap.views.components.admin.side-bar :refer [admin-side-bar]]
            [auto-ap.views.utils :refer [login-url dispatch-event dispatch-value-change bind-field horizontal-field nf with-user]]
            [auto-ap.views.pages.admin.clients.table :as table]
            [auto-ap.views.pages.admin.clients.form :as form]
            [cljs.reader :as edn]
            [auto-ap.routes :as routes]
            [bidi.bidi :as bidi]
            [auto-ap.status :as status]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.pages.admin.clients.side-bar :as side-bar]
            [vimsical.re-frame.fx.track :as track]))

(re-frame/reg-event-db
 ::received-intuit-bank-accounts
 (fn [db [_ result]]
   (assoc db ::subs/intuit-bank-accounts (:intuit-bank-accounts result))))

(re-frame/reg-event-fx
 ::mounted
 [with-user]
 (fn  [{:keys [db user]} _]
   {::track/register {:id ::params
                      :subscription [::params]
                      :event-fn (fn [params] [::params-change params])}
    :graphql {:token user
              :query-obj {:venia/queries [[:intuit_bank_accounts [:external_id :id :name]]]}
              :owns-state {:single [::load-intuit-bank-accounts]}
              :on-success [::received-intuit-bank-accounts]} }))

(re-frame/reg-event-fx
 ::unmounted
 (fn [{:keys [db]} _]
   {:db (dissoc db ::table/params ::side-bar/filter-params)
    ::track/dispose {:id ::params}}))

(re-frame/reg-sub
 ::params
 :<- [::table/params]
 :<- [::side-bar/filter-params]
 (fn [[table-params filter-params]]
   (cond-> {}
     (seq filter-params) (merge filter-params)
     (seq table-params) (merge table-params))))



(re-frame/reg-event-db
 ::new
 (fn  [db [_ client-id]]
   (-> db
       (forms/start-form ::form/form {:bank-accounts []}))))

(re-frame/reg-event-fx
 ::params-change
 (fn [_ [_ params]]
   {:set-uri-params params}))

(re-frame/reg-sub
 ::page
 :<- [::params]
 :<- [::subs/clients]
 (fn [[params all-clients]]
   (let [matching-clients (cond->> all-clients
                            (not-empty (:name params)) (filter #(str/includes? (str/lower-case (or (:name %) ""))
                                                                               (str/lower-case (:name params))))
                            (not-empty (:code params)) (filter #(= (str/lower-case (or (:code %) ""))
                                                                   (str/lower-case (:code params)))))]
     (assoc (grid/virtual-paginate-controls (:start params ) (:per-page params) matching-clients)
            :data (grid/virtual-paginate (:start params) (:per-page params) matching-clients)))))


(def admin-clients-content 
  (with-meta
    (fn []
      [:div
       [:div
        [:h1.title "Clients"]
        [:div.is-pulled-right
         [:a.button.is-primary.is-outlined {:on-click (dispatch-event [::new])} "New client"]]
        [table/clients-table {:page @(re-frame/subscribe [::page])
                              :status @(re-frame/subscribe [::status/single ::page])}]]])
    {:component-did-mount #(re-frame/dispatch [::mounted])
     :component-will-unmount #(re-frame/dispatch-sync [::unmounted])}))


(defn admin-clients-page []
  (let [{:keys [active?]} @(re-frame/subscribe [::forms/form ::form/form])]
    [side-bar-layout {:side-bar [admin-side-bar {}
                                 [side-bar/client-side-bar]]
                      :main [admin-clients-content]
                      :right-side-bar [appearing-side-bar {:visible? active?} [form/new-client-form]] }]))

