<template>
  <div class="container" :class="{ 'responsive': responsive }" @focusout="focusLost">


    <div class="field-group" v-if="!hideDescription">
      <div class="caption-column">Part number</div>
      <div class="input-column">
        <span>{{ partNumber }}</span>
      </div>
    </div>

    <div class="field-group" v-if="!hideDescription">
      <div class="caption-column">Description</div>
      <div class="input-column">
        <span>{{ description }}</span>
      </div>
    </div>

    <div class="field-group">
      <div class="caption-column">HS code</div>
      <div class="input-column">
        <div class="hs-code-container">
          <autosuggest-searchbar ref="hsCodeSearchbar" :activate-watcher="true" :fetch-suggestions="fetchHsCode"
                                 :initial-value="hsCode"
                                 @selected="hsCodeSelected" @blur="hsCodeChanged"
                                 placeholder="Find hs code" no-results-text="Not found."></autosuggest-searchbar>

        </div>
      </div>
    </div>




    <div class="field-group" :class="{ 'disabled': !disableTariff }">
      <div class="caption-column">Tariff rate [%]</div>
      <div class="input-column">
        <div class="text-container input-field-tariffrate">
          <input ref="tariffRateInput" :value="tariffRatePercent" @blur="validateTariffRateEvent"
                 class="input-field"
                 :disabled="!disableTariff"
                 autocomplete="off"/>
          <ph-warning v-if="showTariffWarning" size="18" class="warning-icon"></ph-warning>
          <div v-if="showTariffWarning" class="tariff-rate-info">
            <div>
              <div class="tariff-rate-info-header">
                <ph-warning size="24"></ph-warning>
                <div v-if="tariffIsDefault">
                  <div>Using default value</div>
                  <div class="tariff-rate-info-headerbox">Automatic determination failed</div>
                </div>
                <div v-else>
                  <div>More than one custom measure found</div>
                  <div class="tariff-rate-info-headerbox">Please review carefully</div>
                </div>
              </div>
              <div class="tariff-rate-info-container">
                <template v-for="measure in measures" :key="measure.code">
                  <div class="tariff-rate-info-cell-measure">Measure {{ measure.code }}</div>
                  <div>Regulation {{ measure.regulation }}</div>
                  <div class="tariff-rate-info-cell-tariffrate">{{ measure.tariffRate }}</div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="field-group" v-if="showCheckbox">
      <div class="caption-column"></div>
      <div class="input-column">
        <checkbox :checked="false" @checkbox-changed="checkBoxChanged">tariff lookup on close</checkbox>
      </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, PhWarning} 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";
import Checkbox from "@/components/UI/Checkbox.vue";

export default {
  name: "MaterialEdit",
  components: {
    Checkbox,
    PhWarning,
    SelectMaterial,
    Modal, PhArrowCounterClockwise, ModalDialog, AutosuggestSearchbar, InputField, Flag, IconButton
  },
  emits: ["update:tariffRate", "updateMaterial", "update:partNumber", "update:hsCode", "save", "close", "startLookup"],
  props: {
    description: {
      type: [String, null],
      required: true,
    },
    hsCode: {
      required: true,
      validator: (value) => value === null || typeof value === 'string'
    },
    countryId: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    tariffRate: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    partNumber: {
      type: String,
      required: true,
    },
    hideDescription: {
      type: Boolean,
      default: false,
    },
    responsive: {
      type: Boolean,
      default: true,
    }
  },
  computed: {
    ...mapStores(useMaterialStore, useCustomsStore),
    tariffRatePercent() {
      return ((this.tariffRate ?? null) !== null) ? (this.tariffRate * 100).toFixed(2) : '';
    },
    showTariffWarning() {
      return this.customsStore.showWarning(this.countryId);
    },
    tariffIsDefault() {
      return this.tariffInfo?.default ?? false;
    },
    tariffInfo() {
      return this.customsStore.findByCountryId(this.countryId);
    },
    measures() {
      return this.tariffInfo.measures;
    },
    showCheckbox() {
      return this.countryId === null;
    },
    disableTariff() {
      return !this.doLookup;
    }
  },
  data() {
    return {
      doLookup: false
    }
  },
  created() {
  },
  methods: {
    focusLost(event) {
      if (!this.$el.contains(event.relatedTarget)) {
        this.$emit('save', 'material');
      }
    },
    updateInputValue(inputRef, formattedValue) {
      this.$nextTick(() => {
        if (this.$refs[inputRef] && this.$refs[inputRef].value !== formattedValue) {
          this.$refs[inputRef].value = formattedValue;
        }
      });
    },
    validateTariffRateEvent(event) {
      event.target.value = this.validateTariffRate(event.target.value);
    },
    validateTariffRate(value) {
      const percentValue = parseNumberFromString(value, 2, true);

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

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

      return validatedPercent === null ? null : validatedPercent.toFixed(2);

    },
    roundNumber(number, digits) {
      const multiple = Math.pow(10, digits);
      return Math.round(number * multiple) / multiple;
    },
    async fetchHsCode(query) {
      return await this.customsStore.findHsCode(query);
    },
    hsCodeChanged() {
      const currentValue = this.$refs.hsCodeSearchbar.searchQuery;
      this.$emit("update:hsCode", currentValue);
    },
    async hsCodeSelected(hsCode) {
      let save = false;

      if (hsCode !== this.hsCode) {
        this.$emit("update:hsCode", hsCode)
        save = true;
      }

      if ((this.countryId ?? null) !== null) {
        const query = {hsCode: hsCode, countryIds: [this.countryId]};
        await this.customsStore.findTariffRate(query);
        this.validateTariffRate((this.customsStore.findByCountryId(this.countryId)?.value ?? 0.03) * 100);
        save = true;
      }

      if (save)
        this.$emit('save', 'material');
    },
    checkBoxChanged(checked) {
      this.doLookup = checked
      this.$emit('startLookup', checked);
    }
  }
}
</script>


<style scoped>


.field-group.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.field-group.disabled .caption-column,
.field-group.disabled .input-field {
  color: #9ca3af;
}

.field-group.disabled .text-container {
  background-color: #f3f4f6;
  cursor: not-allowed;
  border-color: #f3f4f6;
}

.input-field:disabled {
  cursor: not-allowed;
  color: #9ca3af;
}

.warning-icon {
  color: #002F54;
}

.text-container:hover .warning-icon {
  transform: scale(1.02);
}

.hs-code-container {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  width: 100%;
  z-index: 1000;
}

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

/* Responsive Layout für Breiten unter 1500px - nur wenn responsive aktiviert ist */
@media (max-width: 1500px) {
  .container.responsive {
    grid-template-columns:
      minmax(auto, max-content)  /* Spalte 1: Label */
      minmax(120px, 1fr)         /* Spalte 2: Input */
      minmax(auto, max-content)  /* Spalte 3: Label */
      minmax(120px, 1fr)         /* Spalte 4: Input/Dropdown */
      minmax(auto, max-content)  /* Spalte 5: Label */
      minmax(120px, 1fr)         /* Spalte 6: Input */
      minmax(auto, max-content)  /* Spalte 7: Label */
      minmax(120px, 1fr); /* Spalte 8: Input/Dropdown */
    grid-template-rows: auto;
    gap: 1.2rem 1rem;
    align-items: center;
  }

  .container.responsive .field-group {
    display: contents;
  }

  .container.responsive .caption-column {
    justify-self: start;
  }

  .container.responsive .input-column {
    min-width: 0;
  }

  .container.responsive .field-group {
    display: contents;
  }

  .container.responsive .caption-column {
    justify-self: start;
  }

  .container.responsive .input-column {
    min-width: 0;
  }
}

.field-group {
  display: contents;
}

.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;
  border: 0.2rem solid #E3EDFF;
  transition: all 0.1s ease;
  flex: 1 1 auto;
  position: relative; /* Hinzufügen */
  z-index: 10;
}

.text-container:hover {
  background: #EEF4FF;
  border: 0.2rem solid #8DB3FE;
  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: 20rem;
  flex: 0 1 10rem;
  position: relative;
}

.tariff-rate-info {
  position: absolute;
  top: 3rem;
  left: -3rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 1.2rem;
  z-index: 5000;
  background-color: #fff;
  border-radius: 0.8rem;
  border: 0.1rem solid #E3EDFF;
  visibility: hidden;
  opacity: 0;
  transform: translateY(-20px);
  padding: 1.6rem 2.4rem;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  min-width: 40rem;
}

.input-field-tariffrate:hover .tariff-rate-info {
  visibility: visible;
  opacity: 1;
  transform: translateY(0);
  transition: opacity 0.5s ease, transform 0.5s ease;
}

.tariff-rate-info-cell-measure {
  font-size: 1.2rem;
  font-weight: 500;
  color: #002F54;
  justify-self: flex-end;
}

.tariff-rate-info-cell-tariffrate {
  justify-self: flex-end;
}

.tariff-rate-info-container {
  margin-top: 2.4rem;
  display: grid;
  grid-template-columns: auto 1fr 1fr;
  gap: 0.8rem;
  font-size: 1.2rem;
  font-weight: 400;
}

.tariff-rate-info-headerbox {
  color: #002F54;
  font-size: 1.2rem;
  font-weight: 400;
}

.tariff-rate-info-header {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  justify-content: flex-start;
  font-size: 1.4rem;
  font-weight: 500;
  background-color: #c3cfdf;
  color: #002F54;
  border-radius: 0.8rem;
  padding: 1.6rem;
  margin-bottom: 1.6rem;
}

/* Optimierung für kleinere Bildschirme unter 1500px - nur wenn responsive aktiviert ist */
@media (max-width: 1500px) {
  .container.responsive .input-field-tariffrate {
    min-width: auto;
    flex: 1 1 auto;
  }
}

</style>