<script setup lang="ts">
import VueDatePicker from '@vuepic/vue-datepicker';
import { axiosInstance, type Contractor, type OrderProduct, type Route } from '@/main'
import { useCategoriesStore } from '@/stores/categories.store'
import { useContractorsStore } from '@/stores/contractors.store'
import { useOrdersStore } from '@/stores/orders.store'
import { storeToRefs } from 'pinia'
import { useSiteControlStore } from '@/stores/siteControl.store'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoutesStore } from '@/stores/routes.store'
import { Order } from '@/main'

const categoriesStore = useCategoriesStore();
const contractorsStore = useContractorsStore();
const ordersStore = useOrdersStore();
const siteControlStore = useSiteControlStore();
const routesStore = useRoutesStore();

const { contractor, contractors } = storeToRefs(contractorsStore);
const { deliveryDate, uuid, order, additionalNotes } = storeToRefs(ordersStore);
const { categories } = storeToRefs(categoriesStore);
const { showConfirmationModal, showCancellationModal, isDarkTheme } = storeToRefs(siteControlStore);
const { route, routes } = storeToRefs(routesStore);

const contractorSearch = ref<string>();
const filteredContractors = ref<Array<Contractor>>();
const showContractorsDropdown = ref<boolean>(false);
const contractorInput = ref(null);

const routeSearch = ref<string>();
const filteredRoutes = ref<Array<Route>>();
const showRoutesDropdown = ref<boolean>(false);
const routeInput = ref(null);
const invoices = ref();

const showErrorNotification = ref<boolean>(false);
const showSuccessNotification = ref<boolean>(false);
const errorNotificationMessage = ref<string>();
const successNotificationMessage = ref<string>();

watch(contractor, (contractor) => {
  if(contractor == undefined) {
    contractorSearch.value = '';
  } else {
    contractorSearch.value = contractor.Knt_NipE + ', ' + contractor.Knt_Nazwa1 + contractor.Knt_Nazwa2 + contractor.Knt_Nazwa3;
  }
}, { immediate: true });

watch(route, (route) => {
  if(route == undefined) {
    routeSearch.value = '';
  } else {
    routeSearch.value = route.MZT_Nazwa1;
  }
}, { immediate: true });

const totalAmountUnpaid = computed(() => {
  let total = 0;
  let totalPaid = 0;
  for(let invoice of invoices.value) {
    total += Number(invoice.BZd_KwotaSys);
    totalPaid += Number(invoice.BZd_KwotaRozSys);
  }
  return (total - totalPaid).toFixed(2);
});

function createJSON(event: Event) {
  event.preventDefault();
  console.log(deliveryDate.value);
  if(typeof deliveryDate.value != typeof Date) {
    deliveryDate.value = new Date(deliveryDate.value as unknown as string);
  }
  const json = {
    MZN_UUID: uuid.value,
    MZN_DataZam: new Date(Date.now()).toISOString(),
    MZN_DataDos: deliveryDate.value != undefined ? deliveryDate.value.toISOString().split('T')[0] : null,
    MZN_PodID: contractor.value?.Knt_KntId,
    MZN_MZTID: route.value?.MZT_MZTID,
    MZN_Uwagi: additionalNotes.value,
    MZamElem: new Array<OrderProduct>
  };

  if(categories.value == undefined) {
    showErrorNotification.value=true;
    errorNotificationMessage.value = "Produkty nie zostały pobrane z bazy danych.";
    return;
  }

  if(contractor.value == undefined) {
    showErrorNotification.value=true;
    errorNotificationMessage.value = "Klient nie został wybrany.";
    return;
  }

  if(deliveryDate.value == undefined) {
    showErrorNotification.value=true;
    errorNotificationMessage.value = "Data dostawy nie została wybrana.";
    return;
  }

  for (let category of categories.value) {
    for (let product of category.Towary) {
      if(product.Quantity != null && product.Quantity != '') {
        if(isNaN(Number(product.Quantity)) || isNaN(Number(product.Twr_CenaZ)) || isNaN(Number(product.Twr_Cena))
          || product.Twr_Cena == "" || product.Twr_CenaZ == "") {
          showErrorNotification.value=true;
          errorNotificationMessage.value = "W zamówieniu znajdują się niepoprawne wartości.";
          return;
        }
        product.Twr_Cena = product.Twr_Cena == "" || product.Twr_Cena == null ? product.BasePrice : product.Twr_Cena;
        product.Twr_CenaZ = product.Twr_CenaZ == "" || product.Twr_CenaZ == null ? product.BasePriceZ : product.Twr_CenaZ;
        const productObject : OrderProduct = {
          MZE_TwrId: product.Twr_TwrId,
          MZE_TwrJm: product.ChosenOption,
          MZE_TwrCena: product.ChosenOption == product.Twr_JMZ ? product.Twr_CenaZ : product.Twr_Cena,
          MZE_TwrIlosc: product.Quantity,
          MZE_TwrNazwa: product.Twr_Nazwa,
          MZE_TwrKod: product.Twr_Kod,
          MZE_MZNID: undefined,
          MZE_MZEID: undefined,
          MZE_TwrStawka: undefined
        };
        json.MZamElem.push(productObject);
      }
    }
  }
  if(json.MZamElem.length == 0) {
    showErrorNotification.value=true;
    errorNotificationMessage.value = "Zamówienie jest puste.";
    return;
  }
  showErrorNotification.value=false;
  console.log(json);
  console.log(JSON.stringify(json));
  axiosInstance.post('/zamowienie', JSON.stringify(json)).then( response => {
    uuid.value = response.data.MZN_UUID;
    order.value = {} as Order;
    order.value.MZN_MZNID = response.data.MZN_MZNID;
    order.value.MZN_Bufor = 1;
    showSuccessNotification.value = true;
    successNotificationMessage.value = "Zamówienie zostało zapisane do bazy danych."
  });
}

function setConfirmationModal(event : Event) {
  event.preventDefault();
  if(uuid.value == undefined) {
    showErrorNotification.value=true;
    errorNotificationMessage.value = "Zamówienie nie zostało jeszcze zapisane w bazie danych.";
    return;
  }
  showConfirmationModal.value = true;
}

function cancelOrder(event: Event) {
  event.preventDefault();
  showCancellationModal.value = true;
}

function filterContractors() {
    if (contractorSearch.value == "") {
      contractor.value = undefined;
      filteredContractors.value = contractors.value;
      return;
    }
    filteredContractors.value = contractors.value.filter(
      contractor =>
      (contractor.Knt_NipE + contractor.Knt_Nazwa1 + contractor.Knt_Nazwa2 + contractor.Knt_Nazwa3).toLowerCase().includes(contractorSearch.value as string)
    );
}

function toggleContractorsDropdown() {
  if(!showContractorsDropdown.value) {
    showContractorsDropdown.value = true;
    if(contractorSearch.value == undefined || contractorSearch.value == '') {
      filteredContractors.value = contractors.value;
    }
  }
}

function selectContractorFromDropdown(selectedContractor : Contractor) {
  console.log(selectedContractor);
  contractor.value = selectedContractor;
  showContractorsDropdown.value = false;
  fetchInvoices();
}

function filterRoutes() {
  if (routeSearch.value == "") {
    route.value = undefined;
    filteredRoutes.value = routes.value;
    return;
  }
  if(routes.value != undefined) {
    filteredRoutes.value = routes.value.filter(
      route =>
        route.MZT_Nazwa1.toLowerCase().includes(routeSearch.value?.toLowerCase() as string)
    );
  }
}

function toggleRoutesDropdown() {
  if(!showRoutesDropdown.value) {
    showRoutesDropdown.value = true;
    if(routeSearch.value == undefined || routeSearch.value == '') {
      filteredRoutes.value = routes.value;
    }
  }
}

function selectRouteFromDropdown(selectedRoute : Route) {
  route.value = selectedRoute;
  showRoutesDropdown.value = false;
}

function handleClickOutsideDropdown(event : Event) {
  if(contractorInput.value != null && !contractorInput.value.contains(event.target)){
    showContractorsDropdown.value = false;
  }
  if(routeInput.value != null && !routeInput.value.contains(event.target)){
    showRoutesDropdown.value = false;
  }
}

async function fetchInvoices() {
  const response = await axiosInstance.get('/zaleglosci/' + contractor.value?.Knt_KntId);
  invoices.value = response.data;

}

onMounted(function (){
  document.addEventListener('click', handleClickOutsideDropdown);
  if(contractor.value != undefined) {
    fetchInvoices();
  }
});

onBeforeUnmount( function () {
  document.removeEventListener('click', handleClickOutsideDropdown);
});
</script>

<template>
  <form class="box is-shadowless" @submit.prevent="createJSON">
    <div>
      <div class="box mb-5">
        <div class="mb-3">
          <h1 class="title is-5" v-if="uuid == undefined"><b>NOWE ZAMÓWIENIE</b></h1>
          <h1 class="title is-5" v-else-if="order != undefined"><b>ZAMÓWIENIE NR {{order.MZN_MZNID}}</b></h1>
        </div>
        <div class="field mb-3">
          <label class="label is-small">Klient</label>
          <div class="field">
            <div ref="contractorInput" class="dropdown maxwidth"
                 v-bind:class="{'is-active': showContractorsDropdown == true}">
              <div class="dropdown-trigger maxwidth" @click="toggleContractorsDropdown">
                <div class="field maxwidth">
                  <p class="control is-expanded has-icons-right is-small maxwidth">
                    <input class="input is-small is-expanded maxwidth" type="search"
                           v-model="contractorSearch" @input="filterContractors" />
                    <span class="icon is-small is-right"><i class="fas fa-search"></i></span>
                  </p>
                </div>
              </div>
              <div class="dropdown-menu is-clipped has-background-info-on-scheme-invert" id="dropdown-menu" role="menu" style="max-width: calc(100vw - 3rem); box-shadow: 0px 0px 6px -1px rgba(165, 165, 165, 0.8); border-radius: 10px 10px 10px 10px; overflow-x:auto">
                <div class="dropdown-content" style="max-height: 50vh; overflow-x: auto">
                  <a v-if="filteredContractors != undefined && filteredContractors.length == 0" class="dropdown-item is-clipped">Brak wyników</a>
                  <a v-for="dropdownContractor in filteredContractors" v-bind:key="dropdownContractor.Knt_KntId"
                     class="dropdown-item is-clipped" @click = "selectContractorFromDropdown(dropdownContractor)"
                     v-bind:class = "{'has-background-info' : dropdownContractor == contractor}">
                    {{dropdownContractor.Knt_NipE + ', ' + dropdownContractor.Knt_Nazwa1 + dropdownContractor.Knt_Nazwa2 + dropdownContractor.Knt_Nazwa3}}
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="field mb-3">
          <DataTable :value="invoices" scrollable v-if="invoices != undefined && invoices.length > 0">
            <Column field="BZd_NumerPelny" header="Numer faktury" frozen/>
            <Column field="BZd_DataDok" header="Data"/>
            <Column field="BZd_Termin" header="Termin zapłaty"/>
            <Column field="BZd_KwotaSys" header="Kwota faktury"/>
            <Column field="BZd_KwotaRozSys" header="Kwota rozliczona"/>
            <ColumnGroup type="footer">
              <Row>
                <Column footer="Kwota zadłużenia" :colspan="4" footerStyle="text-align:right" />
                <Column :footer="totalAmountUnpaid" />
              </Row>
            </ColumnGroup>
          </DataTable>
          <span v-else>Brak nierozliczonych faktur</span>
        </div>
        <div class="field mb-3">
          <label class="label is-small">Data dostawy</label>
          <div class="field is-small">
            <VueDatePicker class ="bulma-is-small"
                           v-model="deliveryDate"
                           :enable-time-picker="false"
                           :clearable="true"
                           input-class-name="input is-small calendar-background"
                           menu-class-name="calendar-background"
                           v-bind:dark = "!!window?.matchMedia?.('(prefers-color-scheme:dark)')?.matches"
            />
          </div>
        </div>
        <div class="field mb-3">
          <label class="label is-small">Trasa</label>
          <div class="field">
            <div ref="routeInput" class="dropdown maxwidth"
                 v-bind:class="{'is-active': showRoutesDropdown == true}">
              <div class="dropdown-trigger maxwidth" @click="toggleRoutesDropdown">
                <div class="field maxwidth">
                  <p class="control is-expanded has-icons-right is-small maxwidth">
                    <input class="input is-small is-expanded maxwidth" type="search"
                           v-model="routeSearch" @input="filterRoutes" />
                    <span class="icon is-small is-right"><i class="fas fa-search"></i></span>
                  </p>
                </div>
              </div>
              <div class="dropdown-menu is-clipped has-background-info-on-scheme-invert" id="dropdown-menu" role="menu" style="max-width: calc(100vw - 3rem); box-shadow: 0px 0px 6px -1px rgba(165, 165, 165, 0.8); border-radius: 10px 10px 10px 10px; overflow-x:auto">
                <div class="dropdown-content" style="max-height: 50vh; overflow-x: auto">
                  <a v-if="filteredRoutes != undefined && filteredRoutes.length == 0" class="dropdown-item is-clipped">Brak wyników</a>
                  <a class="dropdown-item is-clipped" @click = "selectRouteFromDropdown(dropdownRoute)"
                     v-bind:class = "{'has-background-info' : route == null}">Brak</a>
                  <a v-for="dropdownRoute in filteredRoutes" v-bind:key="dropdownRoute.MZT_MZTID"
                     class="dropdown-item is-clipped" @click = "selectRouteFromDropdown(dropdownRoute)"
                     v-bind:class = "{'has-background-info' : dropdownRoute == route}">
                    {{dropdownRoute.MZT_Nazwa1}}
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="field">
          <label class="label is-small">Uwagi do zamówienia</label>
          <textarea
            v-model="additionalNotes"
            class="textarea"
            placeholder="Uwagi do zamówienia"
            rows="5"
          ></textarea>
        </div>
        <button class="button is-info mt-3">Zapisz</button>
        <button class="button is-success mt-3 ml-3" @click="setConfirmationModal" v-bind:disabled="uuid == undefined">Potwierdź</button>
        <button class="button is-danger mt-3 ml-3" @click="cancelOrder" v-bind:disabled="uuid == undefined">Anuluj</button>
        <div v-if="showErrorNotification" class="notification is-danger is-bold mt-3">
          <button  class="delete" @click.prevent="showErrorNotification = false"></button>
          {{ errorNotificationMessage }}
        </div>
        <div v-if="showSuccessNotification" class="notification is-success is-bold mt-3">
          <button  class="delete" @click.prevent="showSuccessNotification = false"></button>
          {{ successNotificationMessage }}
        </div>
      </div>
    </div>
    <div v-for="category in categories" :key="category.Kod">
      <div class="box mb-3" >
        <h1 class="title is-5 mb-3 mb-3"><b>{{ category.Kod }}</b></h1>
        <div class="field" v-for="(product, index) in category.Towary" :key="product.Twr_Nazwa">
          <label class="label is-small">{{ product.Twr_Nazwa }}</label>
          <div class="columns is-mobile">
            <div class="column" v-if="product.ChosenOption == product.Twr_JM">
              <div class="field has-addons">
                <p class="control is-expanded">
                  <input
                    class="input is-small is-fullwidth"
                    type="text"
                    placeholder="Kwota"
                    v-model="product.Twr_Cena"
                    v-bind:class="{ 'is-danger has-background-danger-soft': product.Twr_Cena != undefined && (isNaN(Number(product.Twr_Cena)) || product.Twr_Cena == ''),'is-success has-background-success-soft': product.Quantity != undefined && product.Quantity as unknown as string != '' && !isNaN(Number(product.Quantity))}"
                  />
                </p>
                <p class="control">
                  <button class="button is-small is-danger is-outlined" @click.prevent="product.Twr_Cena = product.BasePrice">X</button>
                </p>
              </div>
            </div>
            <div class="column" v-else-if="product.ChosenOption == product.Twr_JMZ">
              <div class="field has-addons">
                <p class="control is-expanded">
                  <input
                    class="input is-small"
                    type="text"
                    placeholder="Kwota"
                    v-model="product.Twr_CenaZ"
                    v-bind:class="{ 'is-danger has-background-danger-soft': product.Twr_CenaZ != undefined && isNaN(Number(product.Twr_CenaZ)), 'is-success has-background-success-soft': product.Quantity != undefined && product.Quantity as unknown as string != '' && !isNaN(Number(product.Quantity))
                                    }"
                  />
                </p>
                <p class="control">
                  <button class="button is-small is-danger is-outlined" @click.prevent="product.Twr_CenaZ = product.BasePriceZ">X</button>
                </p>
              </div>
            </div>
            <div class="column">
              <div class="field has-addons">
                <p class="control">
                  <span class="select is-small" v-bind:class="{ 'is-danger': product.Quantity != undefined && isNaN(Number(product.Quantity)),'is-success': product.Quantity != undefined && product.Quantity as unknown as string != '' && !isNaN(Number(product.Quantity))}">
                    <select v-model="product.ChosenOption" v-bind:class="{ 'is-danger has-background-danger-soft': product.Quantity != undefined && isNaN(Number(product.Quantity)),'is-success has-background-success-soft': product.Quantity != undefined && product.Quantity as unknown as string != '' && !isNaN(Number(product.Quantity))}">
                      <option v-for="option in product.Options" :key="option">{{ option }}</option>
                    </select>
                  </span>
                </p>
                <p class="control is-expanded">
                  <input class="input is-small" type="text" placeholder="Ilość" v-model="product.Quantity" v-bind:class="{ 'is-danger has-background-danger-soft': product.Quantity != undefined && isNaN(Number(product.Quantity)),'is-success has-background-success-soft': product.Quantity != undefined && product.Quantity as unknown as string != '' && !isNaN(Number(product.Quantity))}">
                </p>
              </div>
            </div>
          </div>
          <div v-if="!(index == category.Towary.length - 1)"></div>
        </div>
      </div>
    </div>
    <div class="columns mt-1 is-variable is-mobile">
      <div class = "column is-6">
        <button class="button is-info is-fullwidth is-large">Zapisz</button>
      </div>
      <div class = "is-large column is-6 ml-3">
        <button class="button is-success is-fullwidth is-large" @click="showConfirmationModal = true">Potwierdź</button>
      </div>
    </div>
  </form>
</template>

<style>
@media (prefers-color-scheme: dark){
  .calendar-background {
    --dp-background-color: rgb(20, 22, 26);
    --dp-border-color: var(--bulma-border);
    --dp-menu-border-color: var(--bulma-border);
    --dp-border-color-hover: var(--bulma-border);
    --dp-border-color-focus: var(--bulma-border);
    --dp-primary-color: var(--bulma-info);
    --dp-primary-text-color: #000;
  }
}

@media (prefers-color-scheme: light){
  .calendar-background {
    --dp-border-color: var(--bulma-border);
    --dp-menu-border-color: var(--bulma-border);
    --dp-border-color-hover: var(--bulma-border);
    --dp-border-color-focus: var(--bulma-border);
    --dp-primary-color: var(--bulma-info);
    --dp-primary-text-color: #000;
  }
}

.maxwidth {
  width: 100%;
}
</style>