<template>
  <div class="dest-mass-handling-container"
       :class="{ 'has-selection': hasSelection, 'apply-filter': applyFilter, 'add-all': addAll }">
    <div>
      <div class="destination-mass-handling-cost-info">
        <ph-warning size="18px"></ph-warning>
        Handling and repackaging costs are calculated automatically.
        If needed, you can overwrite these values here.
      </div>
    </div>
    <div class="destination-mass-handling-checkbox">
      <checkbox :checked="handlingCostActive" @checkbox-changed="activateInputFields">I want to enter handling and
        repackaging costs manually.
      </checkbox>
    </div>
    <div class="dest-mass-handling-table-wrapper" v-if="handlingCostActive">
      <div class="dest-mass-handling-table-header">
        <div class="dest-mass-handling-table-header-checkbox">
          <checkbox @checkbox-changed="updateCheckBoxes" :checked="overallCheck"
                    :indeterminate="overallIndeterminate"></checkbox>
        </div>
        <div class="dest-mass-handling-table-header-material">Material</div>
        <div class="dest-mass-handling-table-header-supplier">Supplier</div>
        <div class="dest-mass-handling-table-header-destination">Destination</div>
        <div class="dest-mass-handling-table-header-applier">
          <icon-button icon="check" :disabled="!someChecked" @click="updateOverallValue"></icon-button>
          <icon-button icon="x" :disabled="!someChecked" @click="dismissChecked"></icon-button>
        </div>
        <div class="dest-mass-handling-table-header-costs">
          <div>Handling costs</div>
          <div class="text-container" :class="{disabled: !someChecked}">
            <input class="input-field"
                   v-model="overallHandlingCostValue"
                   autocomplete="off"
                   @blur="validateHandlingCost($event, 'handling')"
                   :disabled="!someChecked"/>
          </div>
        </div>
        <div class="dest-mass-handling-table-header-costs">
          <div>Repackaging cost</div>
          <div class="text-container" :class="{disabled: !someChecked}">
            <input class="input-field"
                   v-model="overallRepackagingCostValue"
                   autocomplete="off"
                   @blur="validateHandlingCost($event, 'repackaging')"
                   :disabled="!someChecked"/>
          </div>
        </div>
        <div class="dest-mass-handling-table-header-costs">
          <div>Disposal costs</div>
          <div class="text-container" :class="{disabled: !someChecked}">
            <input class="input-field"
                   v-model="overallDisposalCostValue"
                   autocomplete="off"
                   @blur="validateHandlingCost($event, 'disposal')"
                   :disabled="!someChecked"/>
          </div>
        </div>
      </div>
      <div class="dest-mass-handling-table">
        <destination-mass-handling-cost-row @action="onClickAction" @update-selected="updateCheckBox" :row="row"
                                            :key="row.id"
                                            :disabled="someChecked"
                                            v-for="row in rows"></destination-mass-handling-cost-row>
      </div>
    </div>
  </div>
</template>

<script>
import {mapStores} from "pinia";
import {useDestinationEditStore} from "@/store/destinationEdit.js";
import {usePremiseEditStore} from "@/store/premiseEdit.js";
import DestinationMassQuantityRow from "@/components/layout/edit/destination/mass/DestinationMassQuantityRow.vue";
import Checkbox from "@/components/UI/Checkbox.vue";
import IconButton from "@/components/UI/IconButton.vue";
import DestinationMassHandlingCostRow
  from "@/components/layout/edit/destination/mass/DestinationMassHandlingCostRow.vue";
import {parseNumberFromString} from "@/common.js";

export default {
  name: "DestinationMassHandlingCost",
  components: {DestinationMassHandlingCostRow, IconButton, Checkbox, DestinationMassQuantityRow},
  props: {
    premiseIds: {
      type: Array,
      required: true
    },
    onLoadingChange: {
      type: Function,
      default: () => {
      }
    }
  },
  data() {
    return {
      handlingCostActive: false,
      overallDisposalCostValue: null,
      overallRepackagingCostValue: null,
      overallHandlingCostValue: null,
      overallCheck: false,
      overallIndeterminate: false,
      isCtrlPressed: false,
      isShiftPressed: false,
    }
  },
  computed: {
    ...mapStores(useDestinationEditStore, usePremiseEditStore),
    rows() {
      return this.destinationEditStore.getHandlingCostMatrix ?? [];
    },
    allChecked() {
      return this.rows.every(r => r.selected);
    },
    someChecked() {
      return this.rows.some(r => r.selected);
    },
    hasSelection() {
      return !this.addAll && !this.applyFilter && this.someChecked;
    },
    applyFilter() {
      return this.isCtrlPressed && this.isShiftPressed;
    },
    addAll() {
      return this.isCtrlPressed && !this.isShiftPressed;
    }
  },
  async created() {
    this.onLoadingChange(true);
    try {
      await new Promise(resolve => setTimeout(() => {
        this.buildMatrix();
        resolve();
      }, 10));
    } finally {
      this.onLoadingChange(false);

    }
  },
  mounted() {
    window.addEventListener('keydown', this.handleKeyDown);
    window.addEventListener('keyup', this.handleKeyUp);
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
    window.removeEventListener('keyup', this.handleKeyUp);
  },
  methods: {

    activateInputFields(value) {
      this.handlingCostActive = value;
    },
    validateHandlingCost(event, type) {
      const value = event.target.value == null ? null : parseNumberFromString(event.target.value, 0);
      const validatedValue = value == null ? null : Math.max(0, value);
      const stringified = validatedValue === null ? '' : validatedValue.toFixed();


      if (type === 'handling')
        this.overallHandlingCostValue = validatedValue;
      else if (type === 'repackaging')
        this.overallRepackagingCostValue = validatedValue;
      else if (type === 'disposal')
        this.overallDisposalCostValue = validatedValue;

      event.target.value = stringified;
    },
    onClickAction(data) {

      this.rows.forEach(d => {
        d.selected = ((data.column === 'material' && d.material === data.row.material)
            || (data.column === 'supplier' && d.supplierId === data.row.supplierId)
            || (data.column === 'destination' && d.destinationNodeId === data.row.destinationNodeId)
            || (data.action === 'append' && d.selected));
      });

      this.updateOverallCheckBox();
    },


    /* key down/up handler */
    handleKeyDown(event) {
      if (event.key === 'Control') {
        this.isCtrlPressed = true;
      } else if (event.key === 'Shift') {
        this.isShiftPressed = true;
      }

      if (event.key === 'Escape') {
        this.fillData(this.modalType);
        this.modalType = null;
      }

    },
    handleKeyUp(event) {
      if (event.key === 'Control') {
        this.isCtrlPressed = false;
      } else if (event.key === 'Shift') {
        this.isShiftPressed = false;
      }
    },

    updateOverallValue() {

      if (this.overallHandlingCostValue !== null || this.overallDisposalCostValue !== null || this.overallRepackagingCostValue !== null) {

        this.rows
            .filter(row => row.selected)
            .forEach(row => {
              row.handling_costs = this.overallHandlingCostValue ?? row.handling_costs;
              row.disposal_costs = this.overallDisposalCostValue ?? row.disposal_costs;
              row.repackaging_costs = this.overallRepackagingCostValue ?? row.repackaging_costs;
            });

        this.overallHandlingCostValue = null;
        this.overallRepackagingCostValue = null;
        this.overallDisposalCostValue = null;

        this.$forceUpdate();
      }

      this.dismissChecked();
    },
    dismissChecked() {
      this.rows.forEach(row => row.selected = false);
      this.updateOverallCheckBox();
    },

    /* checkbox handling */

    updateCheckBox(data) { // data = {id: this.row.id, selected: value}
      // update global (rest is done in row)
      this.updateOverallCheckBox();
    },
    updateCheckBoxes(value) {
      this.rows?.forEach(r => r.selected = value);
      this.updateOverallCheckBox();

    },
    updateOverallCheckBox() {
      this.overallCheck = this.rows.every(r => r.selected);

      if (!this.overallCheck)
        this.overallIndeterminate = this.rows.some(r => r.selected);

    },
    toNode(node, limit = 5) {
      if (!node)
        return 'N/A';

      const name = node.name;
      const mappingId = node.external_mapping_id;
      const needsShortName = name.length > limit;
      const useMappingId = ((mappingId ?? null) !== null) && ((name ?? null) === null || needsShortName);
      const shortName = name?.substring(0, limit).concat("...") ?? 'N/A';
      return `${useMappingId ? mappingId.replace("_", " ") : (needsShortName ? shortName : name)}`;

    },
    async buildMatrix() {
      const handlingCostMatrix = [];

      for (const pId of this.premiseIds) {
        const premise = this.premiseEditStore.getById(pId);
        const destinations = this.destinationEditStore.getByPremiseId(pId);
        if (!destinations) continue;

        for (const d of destinations) {
          handlingCostMatrix.push({
            id: premise.id,
            material: premise.material.part_number,
            supplier: this.toNode(premise.supplier, 15),
            supplierId: premise.supplier.id,
            supplierIso: premise.supplier.country.iso_code,
            destinationId: d.id,
            destinationNodeId: d.destination_node.id,
            destination: this.toNode(d.destination_node, 15),
            repackaging_costs: d.repackaging_costs,
            handling_costs: d.handling_costs,
            disposal_costs: d.disposal_costs,
            selected: false
          });

          this.handlingCostActive = ((d.handling_costs !== null) || d.repackaging_costs !== null || d.disposal_costs !== null) || this.handlingCostActive;

        }
      }

      this.destinationEditStore.setHandlingCostMatrix(handlingCostMatrix);
      await this.$nextTick();
    }
  }
}
</script>


<style scoped>

.dest-mass-handling-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: auto;
  gap: 2.4rem;
}

.destination-mass-handling-cost-info {
  display: flex;
  align-items: center;
  font-size: 1.4rem;
  gap: 1.6rem;
  background-color: #c3cfdf;
  color: #002F54;
  border-radius: 0.8rem;
  padding: 1.6rem;
  margin: 1.6rem 1.6rem 0 1.6rem;
}

.destination-mass-handling-checkbox {
  display: flex;
  align-items: center;
  gap: 1.6rem;
  padding: 0 1.6rem;
}


/* Global style für copy-mode cursor */
.dest-mass-handling-container.has-selection :deep(.dest-mass-handling-row__cell--copyable:hover) {
  cursor: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDEyOC41MSAxMzQuMDUiPjxkZWZzPjxzdHlsZT4uY3tmaWxsOm5vbmU7fS5jLC5ke3N0cm9rZTojMDEwMTAxO3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZDtzdHJva2Utd2lkdGg6NXB4O30uZHtmaWxsOiNmZmY7fTwvc3R5bGU+PC9kZWZzPjxnIGlkPSJhIj48cGF0aCBjbGFzcz0iYyIgZD0ibTU0Ljg5LDExMi41MWgtMi4yNGMtMS4yNCwwLTIuMjQtMS0yLjI0LTIuMjR2LTIuMjQiLz48bGluZSBjbGFzcz0iYyIgeDE9IjcwLjU3IiB5MT0iNzYuNjciIHgyPSI2My44NSIgeTI9Ijc2LjY3Ii8+PGxpbmUgY2xhc3M9ImMiIHgxPSI3MC41NyIgeTE9IjExMi41MSIgeDI9IjY2LjA5IiB5Mj0iMTEyLjUxIi8+PGxpbmUgY2xhc3M9ImMiIHgxPSI4Ni4yNSIgeTE9Ijk5LjA3IiB4Mj0iODYuMjUiIHkyPSI5Mi4zNSIvPjxsaW5lIGNsYXNzPSJjIiB4MT0iNTAuNDEiIHkxPSI5Ni44MyIgeDI9IjUwLjQxIiB5Mj0iOTIuMzUiLz48cGF0aCBjbGFzcz0iYyIgZD0ibTgxLjc3LDExMi41MWgyLjI0YzEuMjQsMCwyLjI0LTEsMi4yNC0yLjI0di0yLjI0Ii8+PHBhdGggY2xhc3M9ImMiIGQ9Im04MS43Nyw3Ni42N2gyLjI0YzEuMjQsMCwyLjI0LDEsMi4yNCwyLjI0djIuMjQiLz48cGF0aCBjbGFzcz0iYyIgZD0ibTU0Ljg5LDc2LjY3aC0yLjI0Yy0xLjI0LDAtMi4yNCwxLTIuMjQsMi4yNHYyLjI0Ii8+PHBhdGggY2xhc3M9ImMiIGQ9Im04Ni4yNSw5OS4wN2gxMS4yYzEuMjQsMCwyLjI0LTEsMi4yNC0yLjI0di0zMS4zNmMwLTEuMjQtMS0yLjI0LTIuMjQtMi4yNGgtMzEuMzZjLTEuMjQsMC0yLjI0LDEtMi4yNCwyLjI0djExLjIiLz48L2c+PGcgaWQ9ImIiPjxwYXRoIGNsYXNzPSJkIiBkPSJtNDQuMDgsNDQuMDdsMzIuOTQtOS4yYzEuNjktLjUyLDIuNjQtMi4zMSwyLjEyLTQtLjMtLjk4LTEuMDUtMS43NS0yLjAxLTIuMDlMNi43MywyLjY3Yy0xLjY3LS41Ny0zLjQ5LjMzLTQuMDYsMi0uMjMuNjYtLjIzLDEuMzgsMCwyLjA1bDI2LjExLDcwLjRjLjU4LDEuNjcsMi40LDIuNTYsNC4wNywxLjk4Ljk3LS4zMywxLjcxLTEuMTEsMi4wMS0yLjA5bDkuMjItMzIuOTRaIi8+PC9nPjwvc3ZnPg==") 12 12, pointer;
  background-color: #f8fafc;
  border-radius: 0.8rem;
}

/* Global style für filter-mode cursor */
.dest-mass-handling-container.add-all :deep(.dest-mass-handling-row__cell--filterable:hover) {
  cursor: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDEyOC41MSAxMzQuMDUiPjxkZWZzPjxzdHlsZT4uY3tmaWxsOm5vbmU7fS5jLC5ke3N0cm9rZTojMDEwMTAxO3N0cm9rZS1saW5lY2FwOnJ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MSw3MC40Yy41OCwxLjY3LDIuNCwyLjU2LDQuMDcsMS45OC45Ny0uMzMsMS43MS0xLjExLDIuMDEtMi4wOWw5LjIyLTMyLjk0WiIvPjwvZz48L3N2Zz4=") 12 12, pointer;
  background-color: #f8fafc;
  border-radius: 0.8rem;
}

/* Global style für filter-mode cursor */
.dest-mass-handling-container.apply-filter :deep(.dest-mass-handling-row__cell--filterable:hover) {
  cursor: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDEyOC41MSAxMzQuMDUiPjxkZWZzPjxzdHlsZT4uZHtzdHJva2U6IzAwMDt9LmQsLmV7ZmlsbDpub25lO30uZCwuZSwuZntzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLXdpZHRoOjVweDt9LmUsLmZ7c3Ryb2tlOiMwMTAxMDE7fS5me2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PGcgaWQ9ImEiPjxsaW5lIGNsYXNzPSJlIiB4MT0iNzMuMDMiIHkxPSI3NS41NSIgeDI9IjY2LjM4IiB5Mj0iNzUuNTUiLz48bGluZSBjbGFzcz0iZSIgeDE9IjY2LjM4IiB5MT0iMTEyLjE2IiB4Mj0iNzMuMDMiIHkyPSIxMTIuMTYiLz48cGF0aCBjbGFzcz0iZSIgZD0ibTgxLjM1LDc1LjU1aDQuOTljLjkyLDAsMS42Ni43NSwxLjY2LDEuNjZ2NC45OSIvPjxsaW5lIGNsYXNzPSJlIiB4MT0iODguMDEiIHkxPSI5Ny4xOCIgeDI9Ijg4LjAxIiB5Mj0iOTAuNTMiLz48cGF0aCBjbGFzcz0iZSIgZD0ibTgxLjM1LDExMi4xNmg0Ljk5Yy45MiwwLDEuNjYtLjc1LDEuNjYtMS42NnYtNC45OSIvPjxsaW5lIGNsYXNzPSJlIiB4MT0iNTEuNCIgeTE9IjkwLjUzIiB4Mj0iNTEuNCIgeTI9Ijk3LjE4Ii8+PHBhdGggY2xhc3M9ImUiIGQ9Im01OC4wNSwxMTIuMTZoLTQuOTljLS45MiwwLTEuNjYtLjc1LTEuNjYtMS42NnYtNC45OSIvPjxwYXRoIGNsYXNzPSJlIiBkPSJtNTguMDUsNzUuNTVoLTQuOTljLS45MiwwLTEuNjYuNzUtMS42NiwxLjY2djQuOTkiLz48L2c+PGcgaWQ9ImIiPjxwYXRoIGNsYXNzPSJmIiBkPSJtNDQuMDgsNDQuMDdsMzIuOTQtOS4yYzEuNjktLjUyLDIuNjQtMi4zMSwyLjEyLTQtLjMtLjk4LTEuMDUtMS43NS0yLjAxLTIuMDlMNi43MywyLjY3Yy0xLjY3LS41Ny0zLjQ5LjMzLTQuMDYsMi0uMjMuNjYtLjIzLDEuMzgsMCwyLjA1bDI2LjExLDcwLjRjLjU4LDEuNjcsMi40LDIuNTYsNC4wNywxLjk4Ljk3LS4zMywxLjcxLTEuMTEsMi4wMS0yLjA5bDkuMjItMzIuOTRaIi8+PC9nPjxnIGlkPSJjIj48bGluZSBjbGFzcz0iZCIgeDE9Ijk5LjM4IiB5MT0iOTQuMTkiIHgyPSIxMjYuMDEiIHkyPSI5NC4xOSIvPjxsaW5lIGNsYXNzPSJkIiB4MT0iMTEyLjY5IiB5MT0iODAuODciIHgyPSIxMTIuNjkiIHkyPSIxMDcuNTEiLz48L2c+PC9zdmc+") 12 12, pointer;
  background-color: #f8fafc;
  border-radius: 0.8rem;
}

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

.text-container.disabled input {
  cursor: not-allowed;
}


.text-container:hover:not(.disabled) {
  background: #EEF4FF;
  border: 0.2rem solid #8DB3FE;
  transform: scale(1.01);

}


.input-field {
  border: none;
  outline: none;
  background: none;
  resize: none;
  font-family: inherit;
  font-size: 1.4rem;
  color: #002F54;

  max-width: 6rem;
}

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

  max-width: 8rem;

}

.dest-mass-handling-table-wrapper {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  flex: 1;
  min-height: 0; /* Wichtig für Firefox */
}

.dest-mass-handling-table-header {
  display: flex;
  flex-direction: row;
  gap: 1.6rem;
  padding: 1.6rem 2.4rem;
  justify-content: flex-start;

  background-color: #ffffff;
  border-bottom: 1px solid rgba(107, 134, 156, 0.2);
  font-weight: 500;
  font-size: 1.4rem;
  color: #6B869C;
  text-transform: uppercase;
  letter-spacing: 0.08rem;

  flex-shrink: 0; /* Header bleibt fixiert */
}

.dest-mass-handling-table {
  overflow-y: auto;
  margin: 0;
  padding-bottom: 2.4rem;
}

.dest-mass-handling-table-header-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 6rem;
}


.dest-mass-handling-table-header-material {
  width: 14rem;
  display: flex;
  align-items: center;
}

.dest-mass-handling-table-header-supplier {
  width: 18rem;
  display: flex;
  align-items: center;
}

.dest-mass-handling-table-header-destination {
  width: 18rem;
  display: flex;
  align-items: center;
}

.dest-mass-handling-table-header-applier {
  display: flex;
  align-items: center;
  width: 7rem;
  gap: 0.8rem;
}

.dest-mass-handling-table-header-costs {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 25rem;
  gap: 0.8rem;
}

</style>