<template>
  <div @focusout="focusLost">
    <div class="container" :class="{ 'responsive': responsive }">
      <div class="field-group">
        <div class="caption-column">MEK_A [EUR]</div>
        <div class="input-column">
          <div class="text-container">
            <input ref="priceInput" @keydown.enter="handleEnter('priceInput', $event)" :value="priceFormatted" @blur="validatePrice" class="input-field"
                   :placeholder="fromMassEdit ? '<keep>' : ''"
                   autocomplete="off"/>
          </div>
        </div>
      </div>

      <div class="field-group">
        <div class="caption-column">Oversea share [%]</div>
        <div class="input-column">
          <div class="text-container">
            <input ref="overseaShareInput" @keydown.enter="handleEnter('overseaShareInput', $event)" :value="overSeaSharePercent" @blur="validateOverSeaShare" class="input-field"
                   :placeholder="fromMassEdit ? '<keep>' : ''"
                   autocomplete="off"/>
          </div>
        </div>
      </div>

      <div class="field-group">
        <div class="caption-column">Include FCA Fee</div>
        <div class="input-column">
          <tooltip text="Select if a additional FCA has to be added during calculation">
            <checkbox ref="fcaInput" @enter="handleEnter('fcaInput', $event)" @keydown.enter="handleEnter('fcaInput', $event)" :checked="includeFcaFee" @checkbox-changed="updateIncludeFcaFee"></checkbox>
          </tooltip>
        </div>
      </div>
    </div>

  </div>
</template>

<script>


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

export default {
  name: "PriceEdit",
  components: {Tooltip, Checkbox},
  emits: ['update:price', 'update:overSeaShare', 'update:includeFcaFee', 'save'],
  props: {
    price: {
      required: true,
      validator: (value) => value === null || typeof value === 'number'
    },
    overSeaShare: {
      required: true,
      validator: (value) => value === null || typeof value === 'number',
    },
    includeFcaFee: {
      type: [Boolean, null],
      required: true,

    },
    responsive: {
      type: Boolean,
      default: true,
    },
    fromMassEdit: {
      type: Boolean,
      default: false,
    }
  },
  computed: {
    priceFormatted() {
      return this.price?.toFixed(2) ?? '';
    },
    overSeaSharePercent() {
      return ((this.overSeaShare ?? null) !== null) ? (this.overSeaShare * 100).toFixed(2) : '';
    }
  },
  methods: {
    handleEnter(currentRef, event) {
      event.preventDefault();

      // Define the navigation order
      const inputOrder = ['priceInput', 'overseaShareInput', 'fcaInput'];

      const currentIndex = inputOrder.indexOf(currentRef);

      if(currentIndex >= inputOrder.length - 1) {
        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', 'price');
      }
    },
    validatePrice(event) {
      const value = (event.target.value.trim().length === 0) ? null : parseNumberFromString(event.target.value, 2);

      const validatedValue = value === null ? null : Math.max(0, value);

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

      event.target.value = validatedValue?.toFixed(2) ?? '';
    },
    updateIncludeFcaFee(value) {
      this.$emit('update:includeFcaFee', value);
    },
    validateOverSeaShare(event) {

      const percentValue = (event.target.value.trim().length === 0) ? null : parseNumberFromString(event.target.value, 2, true);


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

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


      event.target.value = validatedPercent?.toFixed(2) ?? '';
    }
  }
}
</script>


<style scoped>

.container {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  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;
  }
}

.field-group {
  display: contents;
}

.input-column {
  display: flex;
  justify-content: space-between;
  align-self: center;
  font-size: 1.4rem;
  font-weight: 300;
  color: #6b7280;
  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;
}

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