<template>

  <div class="container" :class="{ 'responsive': responsive }" @focusout="focusLost">
    <div class="caption-column">HU length</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="lengthInput" :value="huLength" @blur="validateDimension('length', $event)"
               @keydown.enter="handleEnter('lengthInput', $event)" class="input-field"
               :placeholder="fromMassEdit ? '<keep>' : ''"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column dimension-unit-label">Dimension unit</div>
    <div class="input-column dimension-unit-dropdown">
      <dropdown :options="huDimensionUnits" v-model="huDimensionUnitSelected"></dropdown>
    </div>


    <div class="caption-column">HU width</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="widthInput" :value="huWidth" @blur="validateDimension('width', $event)"
               @keydown.enter="handleEnter('widthInput', $event)" class="input-field"
               :placeholder="fromMassEdit ? '<keep>' : ''"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column"></div>
    <div class="input-column"></div>


    <div class="caption-column">HU height</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="heightInput" :value="huHeight" @blur="validateDimension('height', $event)"
               @keydown.enter="handleEnter('heightInput', $event)" class="input-field"
               :placeholder="fromMassEdit ? '<keep>' : ''"
               autocomplete="off"/>
      </div>
    </div>
    <div class="caption-column"></div>
    <div class="input-column"></div>


    <div class="caption-column">HU weight</div>
    <div class="input-column">
      <div class="text-container">
        <input ref="weightInput" :value="huWeight" @blur="validateWeight('weight', $event)"
               @keydown.enter="handleEnter('weightInput', $event)" class="input-field"
               :placeholder="fromMassEdit ? '<keep>' : ''"
               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"
               @keydown.enter="handleEnter('unitCountInput', $event)" class="input-field"
               :placeholder="fromMassEdit ? '<keep>' : ''"
               autocomplete="off"/>
      </div>
    </div>

    <div class="input-column-chk">
      <tooltip position="top"
               text="Uncheck for unmixed containers.">
        <checkbox :checked="mixable" @checkbox-changed="updateMixable">Mixable</checkbox>
      </tooltip>
      <tooltip position="left" text="Uncheck 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', 'accept'],
  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,
    },
    responsive: {
      type: Boolean,
      default: true,
    },
    fromMassEdit: {
      type: Boolean,
      default: false,
    }
  },
  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') ? 3 : 0);
    },
    weightDecimals() {
      const unitType = this.huWeightUnits.find(unit => unit.id === this.huWeightUnitSelected)?.value;
      return (unitType === 'kg') ? 3 : ((unitType === 't') ? 6 : 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') ? 3 : 0);

        const parsedLength = (this.length ?? null) === null ? null : parseFloat(this.length.toFixed(decimals));
        this.$emit('update:length', parsedLength);

        const parsedHeight = (this.height ?? null) === null ? null : parseFloat(this.height.toFixed(decimals));
        this.$emit('update:height', parsedHeight);

        const parsedWidth = (this.width ?? null) === null ? null : 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') ? 6 : 0);

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

        this.$emit('update:weightUnit', unitType);
      }
    }
  },
  methods: {
    handleEnter(currentRef, event) {
      event.preventDefault();

      // Define the navigation order
      const inputOrder = ['lengthInput', 'widthInput', 'heightInput', 'weightInput', 'unitCountInput'];

      const currentIndex = inputOrder.indexOf(currentRef);

      if(currentIndex >= inputOrder.length - 1) {
        this.validateCount(event);
        this.$emit('accept');
        return;
      }

      if (currentIndex !== -1 && currentIndex < inputOrder.length - 1) {
        const nextRef = inputOrder[currentIndex + 1];
        this.$nextTick(() => {
          if (this.$refs[nextRef]) {
            this.$refs[nextRef].focus();
            this.$refs[nextRef].select();
          }
        });
      }
    },
    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) ? 3 : 0);
      const parsed = event.target.value.trim().length === 0 ? null : parseNumberFromString(event.target.value, decimals);

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

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

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

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

      // Force update the input field with the correctly formatted value
      const formattedValue = parsed ? 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 auto auto auto;
  grid-template-rows: repeat(5, fit-content(0));
  gap: 1.2rem 1.6rem;
  flex: 0 0 auto;
  width: 100%;
}

/* 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;
  }
  /* First row: Length, Dimension unit, Weight, Weight unit */
  .container.responsive > .caption-column:nth-child(1) { /* Length label */
    grid-column: 1;
    grid-row: 1;
  }

  .container.responsive > .input-column:nth-child(2) { /* Length input */
    grid-column: 2;
    grid-row: 1;
  }

  .container.responsive > .caption-column:nth-child(3) { /* Dimension unit label */
    grid-column: 3;
    grid-row: 1;
  }

  .container.responsive > .input-column:nth-child(4) { /* Dimension unit dropdown */
    grid-column: 4;
    grid-row: 1;
  }

  .container.responsive > .caption-column:nth-child(13) { /* Weight label */
    grid-column: 5;
    grid-row: 1;
  }

  .container.responsive > .input-column:nth-child(14) { /* Weight input */
    grid-column: 6;
    grid-row: 1;
  }

  .container.responsive > .caption-column:nth-child(15) { /* Weight unit label */
    grid-column: 7;
    grid-row: 1;
  }

  .container.responsive > .input-column:nth-child(16) { /* Weight unit dropdown */
    grid-column: 8;
    grid-row: 1;
  }

  /* Second row: Width, Pieces per HU */
  .container.responsive > .caption-column:nth-child(5) { /* Width label */
    grid-column: 1;
    grid-row: 2;
  }

  .container.responsive > .input-column:nth-child(6) { /* Width input */
    grid-column: 2;
    grid-row: 2;
  }

  .container.responsive > .caption-column:nth-child(17) { /* Pieces per HU label */
    grid-column: 5;
    grid-row: 2;
  }

  .container.responsive > .input-column:nth-child(18) { /* Pieces per HU input */
    grid-column: 6;
    grid-row: 2;
  }

  /* Third row: Height, Checkboxes */
  .container.responsive > .caption-column:nth-child(9) { /* Height label */
    grid-column: 1;
    grid-row: 3;
  }

  .container.responsive > .input-column:nth-child(10) { /* Height input */
    grid-column: 2;
    grid-row: 3;
  }

  .container.responsive .input-column-chk {
    grid-column: 7 / -1;
    grid-row: 3;
    justify-content: flex-start;
  }

  /* Hide empty caption and input columns */
  .container.responsive > .caption-column:nth-child(7),
  .container.responsive > .input-column:nth-child(8),
  .container.responsive > .caption-column:nth-child(11),
  .container.responsive > .input-column:nth-child(12) {
    display: none;
  }
}

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

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

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

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