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


      <template v-for="field in displayFields" :key="field.name">
        <div class="caption-column">{{ field.label }}</div>
        <div class="input-column">
          <span v-if="!field.editable">{{ field.value }}</span>
          <div v-else class="hs-code-container">
            <div class="text-container input-field-tariffrate">
              <input
                  :ref="field.ref"
                  :value="field.value"
                  @blur="field.onBlur"
                  class="input-field"
                  autocomplete="off"
                  :placeholder="fromMassEdit ? '<keep>' : ''"
              />
            </div>
          </div>
        </div>
      </template>

    </div>

    <div v-if="tariffUnlocked" class="tariff-rate-info-container">
      <ph-warning size="24" />
      <div>
        <div>Automatic tariff rate determination was ambiguous</div>
        <div class="tariff-rate-info-text">
          Please contact a customs expert to obtain correct HS code and tariff rate.
        </div>
      </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 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"],
  props: {
    description: {
      type: String,
      default: null,
    },
    hsCode: {
      type: String,
      default: null,
    },
    countryId: {
      type: Number,
      default: null,
    },
    tariffUnlocked: {
      type: Boolean,
      required: true,
    },
    tariffRate: {
      type: Number,
      default: null,
    },
    partNumber: {
      type: String,
      required: true,
    },
    hideDescription: {
      type: Boolean,
      default: false,
    },
    responsive: {
      type: Boolean,
      default: true,
    },
    fromMassEdit: {
      type: Boolean,
      default: false,
    }
  },
  computed: {
    ...mapStores(useMaterialStore),

    tariffRatePercent() {
      return this.tariffRate !== null
          ? (this.tariffRate * 100).toFixed(2)
          : '';
    },

    displayFields() {
      const fields = [];

      if (!this.hideDescription) {
        fields.push(
            {
              name: 'partNumber',
              label: 'Part number',
              value: this.partNumber,
              editable: false
            },
            {
              name: 'description',
              label: 'Description',
              value: this.description,
              editable: false
            }
        );
      }

      fields.push(
          {
            name: 'hsCode',
            label: 'HS code',
            value: this.hsCode,
            editable: this.tariffUnlocked,
            ref: 'hsCodeInput',
            onBlur: this.hsCodeChanged
          },
          {
            name: 'tariffRate',
            label: 'Tariff rate [%]',
            value: this.tariffRatePercent,
            editable: this.tariffUnlocked,
            ref: 'tariffRateInput',
            onBlur: this.validateTariffRateEvent
          }
      );

      return fields;
    }
  },
  created() {
  },
  methods: {
    focusLost(event) {
      if (!this.$el.contains(event.relatedTarget)) {
        this.$emit('save', 'material');
      }
    },

    validateTariffRateEvent(event) {
      event.target.value = this.validateTariffRate(event.target.value);
    },

    validateTariffRate(value) {
      const percentValue = parseNumberFromString(value, 2, true);
      const validatedPercent = this.clampValue(percentValue, 0, 999.99);
      const validatedDecimal = validatedPercent !== null ? validatedPercent / 100 : null;

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

      return validatedPercent?.toFixed(2) ?? null;
    },

    clampValue(value, min, max) {
      return value === null ? null : Math.max(min, Math.min(max, value));
    },

    roundNumber(number, digits) {
      if (number === null) return null;
      const multiple = 10 ** digits;
      return Math.round(number * multiple) / multiple;
    },
    hsCodeChanged(event) {
      let sanitized = event.target.value
          .replace(/\D/g, '')
          .substring(0, 10)

      if(sanitized.length !== 0)
        sanitized = sanitized.padEnd(10, '0');
      else
        sanitized = null;

      this.$emit("update:hsCode", sanitized);
      event.target.value = sanitized;
    }
  }
}
</script>


<style scoped>

.outer-container {
  display: flex;
  flex-direction: column;
  gap: 3.2rem;
  flex: 1 1 auto;

}

.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;
}

@media (max-width: 1500px) {
  .container.responsive {
    grid-template-columns:
      minmax(auto, max-content)
      minmax(120px, 1fr)
      minmax(auto, max-content)
      minmax(120px, 1fr)
      minmax(auto, max-content)
      minmax(120px, 1fr)
      minmax(auto, max-content)
      minmax(120px, 1fr);
    grid-template-rows: auto;
    gap: 1.2rem 1rem;
    align-items: center;
  }

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

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

  .container.responsive .input-field-tariffrate {
    min-width: auto;
    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;
  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-text {
  color: #002F54;
  font-size: 1.2rem;
  font-weight: 400;
}

.tariff-rate-info-container {
  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;
}


</style>