<template>
  <div class="start-calculation-container">
    <h2 class="page-header">Create Calculation</h2>


    <div class="part-numbers-headers">
      <h3 class="sub-header">Part Numbers</h3>
      <basic-button icon="CloudArrowUp" :showIcon="true" @click="activateModal('partNumber')">Drop part numbers
      </basic-button>
    </div>

    <ul class="item-list">
      <li class="item-list-element" v-for="material in assistantStore.materials" :key="material.id">
        <material-item :part-number="material['part_number']" :name="material.name" :id="material.id"
                       @delete="deleteMaterial"></material-item>
      </li>
    </ul>

    <modal :state="showPartNumberModal" @close="closeModal('partNumber')" :close-on-backdrop="false">
      <div class="part-number-modal-container">
        <h3 class="sub-header">Drop part numbers here</h3>
        <div class="part-number-drop-container">
          <textarea v-model="partNumberField" name="partNumbers" cols="140" rows="15"></textarea>
        </div>
        <div class="part-number-modal-action">
          <basic-button @click="parsePartNumbers" icon="CloudArrowUp">Analyze input</basic-button>
          <basic-button @click="closeModal('partNumber')" :show-icon="false" variant="secondary">Cancel</basic-button>
        </div>
      </div>
    </modal>

    <div class="supplier-headers">
      <h3 class="sub-header">Suppliers</h3>
      <div class="supplier-headers-searchbar-container">
        <autosuggest-searchbar @selected="selectedSupplier" placeholder="Search and add supplier ..."
                               no-results-text='No supplier found for "{query}".' :fetch-suggestions="fetch"
                               variant="flags" :reset-on-select="true"
                               :flag-resolver="resolveFlag" title-resolver="name"
                               subtitle-resolver="address"></autosuggest-searchbar>

      </div>
      <basic-button icon="plus" @click="activateModal('newSupplier')">Create a new supplier</basic-button>
    </div>

    <ul class="item-list">
      <li class="item-list-element" v-for="supplier in assistantStore.suppliers" :key="supplier.id">
        <supplier-item :id="supplier.id" :iso-code="supplier.iso" :address="supplier.address"
                       :name="supplier.name" @delete="deleteSupplier"
                       :is-user-supplier="supplier.isUserSupplier"></supplier-item>
      </li>
    </ul>

    <modal :close-on-backdrop="false" :state="newSupplierModalState" @close="closeModal('newSupplier')">
      <create-new-node @created="addCreatedNode" @close="closeModal('newSupplier')"></create-new-node>
    </modal>


    <div class="start-calculation-footer-container">
      <div class="start-calculation-footer-left">
        This will create {{ assistantStore.count }} calculations.
      </div>
      <div class="start-calculation-footer-right">
        <checkbox :checked="!this.assistantStore.createEmpty" @checkbox-changed="setUseExisting">Import data from
          existing calculations
        </checkbox>
        <basic-button :disabled="assistantStore.count==0" @click="createPremises" variant="secondary"
                      :show-icon="false">Create
        </basic-button>
      </div>
    </div>
  </div>


</template>


<script>

import AutosuggestSearchbar from "@/components/UI/AutoSuggestSearchBar.vue";
import {mapStores} from "pinia";
import {useNodeStore} from "@/store/node.js";
import BasicButton from "@/components/UI/BasicButton.vue";
import MaterialItem from "@/components/layout/assistant/MaterialItem.vue";
import SupplierItem from "@/components/layout/assistant/SupplierItem.vue";
import Modal from "@/components/UI/Modal.vue";
import {useAssistantStore} from "@/store/assistant.js";
import CreateNewNode from "@/components/layout/node/CreateNewNode.vue";
import Checkbox from "@/components/UI/Checkbox.vue";
import {UrlSafeBase64} from "@/common.js";
import {useNotificationStore} from "@/store/notification.js";


export default {
  name: "CalculationAssistant",
  components: {Checkbox, CreateNewNode, Modal, SupplierItem, MaterialItem, BasicButton, AutosuggestSearchbar},
  computed: {
    ...mapStores(useNodeStore, useAssistantStore, useNotificationStore),
    showPartNumberModal() {
      return this.partNumberModalState;
    }
  },
  data() {
    return {
      newSupplierModalState: false,
      partNumberModalState: true,
      partNumberField: '',
      createMsg: 'Creating calculations ...'
    }
  },
  methods: {
    setUseExisting(useExisting) {
      this.assistantStore.setCreateEmpty(!useExisting);
    },
    async createPremises() {

      this.notificationStore.setSpinner(this.createMsg);

      const ids = await this.assistantStore.createPremises();

      if (ids.length === 1) {
        this.$router.push({name: "edit", params: {id: new UrlSafeBase64().encodeIds([ids[0]])}});
      } else {
        this.$router.push({name: "bulk", params: {ids: new UrlSafeBase64().encodeIds(ids)}});
      }

      this.notificationStore.clearSpinner();

      this.assistantStore.reset();
    },
    selectedSupplier(supplier) {
      this.assistantStore.addSupplier(supplier);
    },
    deleteMaterial(id) {
      this.assistantStore.deleteMaterial(id);
    },
    deleteSupplier(id) {
      this.assistantStore.deleteSupplier(id);
    },
    async fetch(query) {
      const supplierQuery = {searchTerm: query, includeUserNode: true, nodeType: "SOURCE"};
      await this.nodeStore.setSearch(supplierQuery);
      return this.nodeStore.nodes;
    },
    resolveFlag(node) {
      return node.country.iso_code;
    },
    activateModal(modalType) {
      if (modalType === "partNumber")
        this.partNumberModalState = true;
      else if (modalType === "newSupplier")
        this.newSupplierModalState = true;

    },
    closeModal(modalType) {
      if (modalType === "partNumber")
        this.partNumberModalState = false;
      else if (modalType === "newSupplier")
        this.newSupplierModalState = false;
    },
    parsePartNumbers() {
      this.closeModal('partNumber');

      if(this.partNumberField.trim().length !== 0)
        this.assistantStore.getMaterialsAndSuppliers(this.partNumberField);

      this.partNumberField = '';
    },
    addCreatedNode(supplier) {
      this.closeModal('newSupplier')
      this.assistantStore.addSupplier(supplier);
    }
  },
  created() {
    this.nodeStore.loadNodes();
  }
}
</script>


<style scoped>

.start-calculation-footer-container {
  display: flex;
  justify-content: space-between;
  gap: 1.6rem;
}

.start-calculation-footer-left {
  font-weight: 400;
  font-size: 1.4rem;
  color: #6B869C;
}

.start-calculation-footer-right {
  display: flex;
  gap: 1.6rem;
}


.part-number-drop-container {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 0.4rem;
  padding: 0.6rem 1.2rem;
  /* box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);*/
  border: 0.2rem solid #E3EDFF;
  transition: all 0.1s ease;
  flex: 1 0 auto;
}

.part-number-drop-container:hover {
  background: #EEF4FF;
  border: 0.2rem solid #8DB3FE;
  /*transform: translateY(2px);*/
  transform: scale(1.01);
}

textarea {
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #002F54;
}

.part-number-modal-container {
  display: flex;
  flex-direction: column;
  gap: 1.6rem;
}

.part-number-modal-action {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 1.6rem
}

.part-numbers-headers {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.6rem;
}

.item-list {
  display: flex;
  list-style: none;
  gap: 2.4rem 2.4rem;
  margin: 4.8rem;
  flex-wrap: wrap;
}

.item-list-element {
  display: flex;
  justify-content: space-between;
}

.supplier-headers {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 1rem;
  gap: 2.4rem;
}

.supplier-headers-searchbar-container {
  flex: 0 0 60rem;
}

</style>