<template>
  <div class="container" @focusout="focusLost">
    <div class="caption-column">Length</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="lengthInput" :value="huLength" @blur="validateDimension('length', $event)" class="input-field"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column">Dimension Unit</div>
    <div class="input-column">
      <dropdown :options="huDimensionUnits" v-model="huDimensionUnitSelected"></dropdown>
    </div>


    <div class="caption-column">Width</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="widthInput" :value="huWidth" @blur="validateDimension('width', $event)" class="input-field"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column"></div>
    <div class="input-column"></div>


    <div class="caption-column">Height</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="heightInput" :value="huHeight" @blur="validateDimension('height', $event)" class="input-field"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column"></div>
    <div class="input-column"></div>


    <div class="caption-column">Weight</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="weightInput" :value="huWeight" @blur="validateWeight('weight', $event)" class="input-field"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column">Weight Unit</div>
    <div class="input-column">
      <dropdown :options="huWeightUnits" v-model="huWeightUnitSelected"></dropdown>
    </div>

    <div class="caption-column">Pieces per HU</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="unitCountInput" :value="huUnitCount" @blur="validateCount" class="input-field"
               autocomplete="off"/>
      </div>
    </div>

    <div class="input-column-chk">
      <tooltip position="left"
               text="Deselect if the handling unit cannot be transported together with other handling units">
        <checkbox :checked="mixable" @checkbox-changed="updateMixable">mixable</checkbox>
      </tooltip>
      <tooltip position="left" text="Deselect if the handling unit cannot be stacked">
        <checkbox :checked="stackable" @checkbox-changed="updateStackable" :disabled="mixable">stackable</checkbox>
      </tooltip>
    </div>
  </div>
</template>

<script>


import Checkbox from "@/components/UI/Checkbox.vue";
import Dropdown from "@/components/UI/Dropdown.vue";
import Tooltip from "@/components/UI/Tooltip.vue";
import {parseNumberFromString} from "@/common.js";

export default {
  name: "PackagingEdit",
  components: {Tooltip, Dropdown, Checkbox},
  emits: ['update:stackable', 'update:mixable', 'update:length', 'update:width', 'update:height', 'update:weight', 'update:unitCount', 'update:weightUnit', 'update:dimensionUnit', 'save'],
  props: {
    length: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    width: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    height: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    weight: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    dimensionUnit: {
      required: true,
      validator: (value) => value === null || typeof value === 'string'
    },
    weightUnit: {
      required: true,
      validator: (value) => value === null || typeof value === 'string'
    },
    unitCount: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    mixable: {
      type: Boolean,
      required: true,
    },
    stackable: {
      type: Boolean,
      required: true,
    }
  },
  computed: {
    huWeight() {
      return this.weight?.toFixed(this.weightDecimals) ?? '';
    },
    huLength() {
      return this.length?.toFixed(this.dimensionDecimals) ?? '';
    },
    huWidth() {
      return this.width?.toFixed(this.dimensionDecimals) ?? '';
    },
    huHeight() {
      return this.height?.toFixed(this.dimensionDecimals) ?? '';
    },
    huUnitCount() {
      return this.unitCount ?? '';
    },
    dimensionDecimals() {
      const unitType = this.huDimensionUnits.find(unit => unit.id === this.huDimensionUnitSelected)?.value;
      return (unitType === 'cm') ? 2 : ((unitType === 'm') ? 4 : 0);
    },
    weightDecimals() {
      const unitType = this.huWeightUnits.find(unit => unit.id === this.huWeightUnitSelected)?.value;
      return (unitType === 'kg') ? 4 : ((unitType === 't') ? 8 : 0);
    },
    huDimensionUnitSelected: {
      get() {
        if (!this.dimensionUnit)
          this.$emit('update:dimensionUnit', 'mm');

        return this.huDimensionUnits.find(unit => unit.value.toLowerCase() === (this.dimensionUnit?.toLowerCase() ?? 'mm'))?.id;

      },
      set(value) {
        const unitType = this.huDimensionUnits.find(unit => unit.id === value)?.value;
        const decimals = (unitType === 'cm') ? 2 : ((unitType === 'm') ? 4 : 0);

        if (this.length) {
          const parsedLength = parseFloat(this.length.toFixed(decimals));
          this.$emit('update:length', parsedLength);
        }

        if (this.height) {
          const parsedHeight = parseFloat(this.height.toFixed(decimals));
          this.$emit('update:height', parsedHeight);
        }

        if (this.weight) {
          const parsedWidth = parseFloat(this.width.toFixed(decimals));
          this.$emit('update:width', parsedWidth);
        }

        this.$emit('update:dimensionUnit', unitType);
      }
    },
    huWeightUnitSelected: {
      get() {
        if (!this.weightUnit)
          this.$emit('update:weightUnit', 'kg');

        return this.huWeightUnits.find(unit => unit.value.toLowerCase() === (this.weightUnit?.toLowerCase() ?? 'kg'))?.id;
      },
      set(value) {
        const unitType = this.huWeightUnits.find(unit => unit.id === value)?.value;
        const decimals = (unitType === 'kg') ? 4 : ((unitType === 't') ? 8 : 0);

        if (this.weight) {
          const parsedWeight = parseFloat(this.weight.toFixed(decimals));
          this.$emit('update:weight', parsedWeight);
        }

        this.$emit('update:weightUnit', unitType);
      }
    }
  },
  methods: {
    focusLost(event) {
      if (!this.$el.contains(event.relatedTarget)) {
        this.$emit('save', 'packaging');
      }
    },
    updateInputValue(inputRef, formattedValue) {
      this.$nextTick(() => {
        if (this.$refs[inputRef] && this.$refs[inputRef].value !== formattedValue) {
          this.$refs[inputRef].value = formattedValue;
        }
      });
    },
    validateDimension(type, event) {
      const decimals = (this.huDimensionUnitSelected === 2) ? 2 : ((this.huDimensionUnitSelected === 3) ? 4 : 0);
      const parsed = parseNumberFromString(event.target.value, decimals);


      this.$emit(`update:${type}`, parsed);

      // Force update the input field with the correctly formatted value
      const formattedValue = parsed.toFixed(decimals);
      const inputRef = `${type}Input`;
      this.updateInputValue(inputRef, formattedValue);
    },
    validateWeight(type, event) {
      const decimals = (this.huWeightUnitSelected === 2) ? 4 : ((this.huWeightUnitSelected === 3) ? 8 : 0);
      const parsed = parseNumberFromString(event.target.value, decimals);

      this.$emit('update:weight', parsed);

      // Force update the input field with the correctly formatted value
      const formattedValue = parsed.toFixed(decimals);
      this.updateInputValue('weightInput', formattedValue);
    },
    validateCount(event) {
      const parsed = parseNumberFromString(event.target.value, 0);
      this.$emit('update:unitCount', parsed);

      // Force update the input field with the correctly formatted value
      const formattedValue = parsed.toString();
      this.updateInputValue('unitCountInput', formattedValue);
    },
    updateStackable(value) {
      this.$emit('update:stackable', value);
    },
    updateMixable(value) {

      if(value)
        this.updateStackable(true);

      this.$emit('update:mixable', value);
    },
  },
  data() {
    return {
      huDimensionUnits: [{id: 1, value: "mm"}, {id: 2, value: "cm"}, {id: 3, value: "m"}],
      huWeightUnits: [{id: 1, value: "g"}, {id: 2, value: "kg"}, {id: 3, value: "t"}],
    }
  }
}
</script>


<style scoped>
.container {
  display: grid;
  grid-template-columns: auto 1fr auto auto;
  grid-template-rows: repeat(5, fit-content(0));
  gap: 1.2rem 1.6rem;
  flex: 1 1 auto;
}

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

.input-column-chk {
  display: flex;
  justify-content: flex-end;
  align-self: center;
  grid-column: -3/-1;
  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;
}

.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: 0 1 min(30rem, 100%);

}

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