<template>
  <div class="container" @focusout="focusLost">

    <div class="caption-column">Part number</div>

    <div class="input-column">

      <span>{{ partNumber }}</span>

      <modal :state="modalSelectMaterial" @close="closeEditModal">
        <select-material :part-number="partNumber" @close="modalEditClick"/>
      </modal>
      <icon-button icon="pencil-simple" @click="activateEditMode"></icon-button>
    </div>


    <div class="caption-column">Description</div>


    <div class="input-column">
      <span>{{ description }}</span>
    </div>


    <div class="caption-column">HS code</div>


    <div class="input-column">
      <div class="hs-code-container">
        <autosuggest-searchbar :activate-watcher="true" :fetch-suggestions="fetchHsCode" :initial-value="hsCode"
                               placeholder="Find hs code" no-results-text="Not found."></autosuggest-searchbar>
        <icon-button icon="ArrowCounterClockwise"></icon-button>
      </div>


      <div class="caption-column">Tariff rate [%]</div>
      <div class="text-container input-field-tariffrate">
        <input ref="tariffRateInput" :value="tariffRatePercent" @blur="validateTariffRate"
               class="input-field"
               autocomplete="off"/>
      </div>
    </div>


  </div>
</template>

<script>


import IconButton from "@/components/UI/IconButton.vue";
import Flag from "@/components/UI/Flag.vue";
import InputField from "@/components/UI/InputField.vue";
import AutosuggestSearchbar from "@/components/UI/AutoSuggestSearchBar.vue";
import ModalDialog from "@/components/UI/ModalDialog.vue";
import {PhArrowCounterClockwise} from "@phosphor-icons/vue";
import {useMaterialStore} from "@/store/material.js";
import {mapStores} from "pinia";
import {parseNumberFromString} from "@/common.js";
import Modal from "@/components/UI/Modal.vue";
import SelectMaterial from "@/components/layout/material/SelectMaterial.vue";
import {useCustomsStore} from "@/store/customs.js";

export default {
  name: "MaterialEdit",
  components: {
    SelectMaterial,
    Modal, PhArrowCounterClockwise, ModalDialog, AutosuggestSearchbar, InputField, Flag, IconButton
  },
  emits: ["update:tariffRate", "updateMaterial", "update:partNumber", "update:hsCode", "save", "close"],
  props: {
    description: {
      type: String,
      required: true,
    },
    hsCode: {
      required: true,
      validator: (value) => value === null || typeof value === 'string'
    },
    tariffRate: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    partNumber: {
      type: String,
      required: true,
    },
    openSelectDirect: {
      type: Boolean,
      default: false,
    }
  },
  computed: {
    ...mapStores(useMaterialStore, useCustomsStore),
    tariffRatePercent() {
      return this.tariffRate ? (this.tariffRate * 100).toFixed(2) : '';
    }
  },
  data() {
    return {
      modalSelectMaterial: false,
    }
  },
  created() {
    this.modalSelectMaterial = this.openSelectDirect;
  },
  methods: {
    focusLost(event) {
      if (!this.$el.contains(event.relatedTarget)) {
        this.$emit('save', 'material');
      }
    },
    closeEditModal() {
      this.modalSelectMaterial = false;
      if (this.openSelectDirect) {
        this.$emit('close');
      }
    },
    modalEditClick(data) {
      this.modalSelectMaterial = false;

      if (data.action === 'accept') {
        this.selectedMaterial = data.material;
        this.$emit('updateMaterial', data.material.id, data.updateMasterData ? 'updateMasterData' : 'keepMasterData');
      } else if (this.openSelectDirect) {
        this.$emit('close');
      }
    },
    updateInputValue(inputRef, formattedValue) {
      this.$nextTick(() => {
        if (this.$refs[inputRef] && this.$refs[inputRef].value !== formattedValue) {
          this.$refs[inputRef].value = formattedValue;
        }
      });
    },
    validateTariffRate(event) {
      const percentValue = parseNumberFromString(event.target.value, 4);

      const validatedPercent = Math.max(0, Math.min(999.99, percentValue));
      const validatedDecimal = validatedPercent / 100;

      if (validatedDecimal !== this.tariffRate) {
        this.$emit('update:tariffRate', validatedDecimal);
      }

      event.target.value = validatedPercent.toFixed(2);
    },
    activateEditMode() {
      this.modalSelectMaterial = true;
    },
    async fetchHsCode(query) {
      const hsCodeQuery = {searchTerm: query};
      await this.customsStore.setQuery(hsCodeQuery);
      return this.customsStore.hsCodes;
    }
  }
}
</script>


<style scoped>

.hs-code-container {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.container {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: repeat(3, fit-content(0));
  gap: 1.6rem;
  flex: 1 1 auto;
}

.input-column {
  display: flex;
  justify-content: space-between;
  align-self: center;
  font-size: 1.4rem;
  font-weight: 300;
  color: #6b7280;
  gap: 1.6rem;
}

.input-field {
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #002F54;
  width: 100%;
}

.text-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 1 auto;
}

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

.caption-column {
  font-size: 1.4rem;
  font-weight: 500;
  align-self: center;
  justify-self: end;
  color: #001D33;
  text-wrap: nowrap;
}

.input-field-tariffrate {
  min-width: 10rem;
  flex: 0 1 10rem;
}

</style>