<template>
  <div class="dest-mass-create-container">
    <autosuggest-searchbar @selected="selectedNode" placeholder="Search and add destination ..."
                           no-results-text='No destination found for "{query}".' :fetch-suggestions="fetch"
                           variant="flags" :reset-on-select="true"
                           :flag-resolver="resolveFlag" title-resolver="name"
                           subtitle-resolver="address"></autosuggest-searchbar>

    <div class="dest-mass-create-table-wrapper">
      <div class="dest-mass-create-table-header">
        <div class="dest-mass-create-table-header-material">Material</div>
        <div class="dest-mass-create-table-header-supplier">Supplier</div>
        <div class="dest-mass-create-table-header-dest"
             :key="`${dest.id}-${dest.overallCheck}-${dest.overallIndeterminate}`"
             v-for="dest in destPool">
          <checkbox :checked="dest.overallCheck" :indeterminate="dest.overallIndeterminate"
                    @checkbox-changed="updateOverallCheck($event, dest.id)"></checkbox>
          {{ toNode(dest, 6) }}
        </div>
      </div>
      <div class="dest-mass-create-table">
        <dest-mass-create-row @update-selected="updateCheck" :row="row" :key="row.id"
                              v-for="row in destMatrix"></dest-mass-create-row>
      </div>
    </div>

  </div>
</template>

<script>
import AutosuggestSearchbar from "@/components/UI/AutoSuggestSearchBar.vue";
import {mapStores} from "pinia";
import {useNodeStore} from "@/store/node.js";
import DestMassCreateRow from "@/components/layout/edit/destination/mass/DestMassCreateRow.vue";
import {useDestinationEditStore} from "@/store/destinationEdit.js";
import {usePremiseEditStore} from "@/store/premiseEdit.js";
import Checkbox from "@/components/UI/Checkbox.vue";

export default {
  name: "DestinationMassCreate",
  components: {Checkbox, DestMassCreateRow, AutosuggestSearchbar},
  computed: {
    ...mapStores(useNodeStore, useDestinationEditStore, usePremiseEditStore),
    premises() {
      return this.premiseEditStore.getPremisses;
    },

  },
  created() {
    this.buildMatrix();
  },
  data() {
    return {
      destPool: [],
      destMatrix: null
    };
  },
  methods: {
    getDestinationChanges() {
      return this.destMatrix;
    },
    buildMatrix() {
      this.destPool = [];
      const destIds = new Set();

      this.premises.forEach(p => {
        this.destinationEditStore.getByPremiseId(p.id)?.forEach(d => {
          const destId = d.destination_node.id;
          if (!destIds.has(destId)) {
            destIds.add(destId);
            this.destPool.push({...d.destination_node, overallCheck: false, overallIndeterminate: false});
          }
        });
      });

      // Build matrix
      this.destMatrix = this.premises
          .filter(p => p)
          .map(premise => {
            const existingDestIds = new Set(
                this.destinationEditStore.getByPremiseId(premise.id)
                    ?.map(d => d.destination_node.id) ?? []
            );

            return {
              id: premise.id,
              material: premise.material.part_number,
              supplier: this.toNode(premise.supplier, 30),
              destinations: this.destPool.map(dest => ({
                ...dest,
                selected: existingDestIds.has(dest.id)
              }))
            };
          });

      // set overall checkboxes
      this.destPool.forEach(dest => {
        const selectedCount = this.destMatrix.filter(r =>
            r.destinations.some(d => d.id === dest.id && d.selected)
        ).length;

        const totalCount = this.destMatrix.length;

        dest.overallCheck = selectedCount === totalCount;
        dest.overallIndeterminate = selectedCount > 0 && selectedCount < totalCount;
      });
    },
    updateCheck(data) {
      const dest = this.destPool.find(d => d.id === data.dest);

      const selectedCount = this.destMatrix.filter(r =>
          r.destinations.some(d => d.id === data.dest && d.selected)
      ).length;

      const totalCount = this.destMatrix.length;

      dest.overallCheck = selectedCount === totalCount;
      dest.overallIndeterminate = selectedCount > 0 && selectedCount < totalCount;

      this.$forceUpdate();

    },
    selectedNode(destination) {
      if (destination && !this.destPool.find(d => d.id === destination.id)) {
        this.destPool.push({
          ...destination,
          overallCheck: false,
          overallIndeterminate: false
        });

        this.destMatrix.forEach(p => p.destinations.push({...destination, selected: false}));
      }
    },
    updateOverallCheck(newValue, id) {
      this.destPool.find(d => d.id === id).overallCheck = newValue;
      this.destMatrix.forEach(r => r.destinations.find(d => d.id === id).selected = newValue);
    },
    async fetch(query) {
      const supplierQuery = {searchTerm: query, includeUserNode: true, nodeType: "DESTINATION"};
      await this.nodeStore.setSearch(supplierQuery);
      return this.nodeStore.nodes;
    },
    resolveFlag(node) {
      return node.country.iso_code;
    },
    toNode(node, limit = 15) {
      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)}`;

    },

  }

}

</script>

<style scoped>

.dest-mass-create-container {
  min-width: 100rem;
  width: 90vw;
  display: flex;
  flex-direction: column;
  max-height: 80vh; /* Begrenzt die Gesamthöhe */
}

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

.dest-mass-create-table-header {
  display: flex;
  flex-direction: row;
  gap: 1.6rem;
  padding: 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-create-table {
  overflow-y: auto;
  margin: 0;
  padding-bottom: 2.4rem;
}

.dest-mass-create-table-header-material {
  width: 14rem;
}

.dest-mass-create-table-header-supplier {
  width: 24rem;
}

.dest-mass-create-table-header-dest {
  display: flex;
  justify-content: flex-start;
  width: 15rem;
}

</style>