<template>
  <div class="bulk-edit-row" @wheel="handleWheel">
    <div class="bulk-edit-row__checkbox">
      <checkbox :checked="isSelected" @checkbox-changed="updateSelected"></checkbox>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div
          class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--clickable bulk-edit-row__cell--filterable edit-calculation-list-header-cell--copyable"
          @click="action($event,'material')"
          @mousedown="handleMouseDown">
        <div class="bulk-edit-row__data">
          <div class="bulk-edit-row__line">
            <ph-package size="16"/>
            {{ premise.material.part_number ?? 'N/A' }}
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            HS:
            {{ premise.hs_code ?? 'N/A' }}
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <ph-hand-coins size="16"/>
            {{ toPercent(premise.tariff_rate) ?? 'N/A' }}
          </div>
        </div>
        <div class="bulk-edit-row__status">
          <transition name="badge-transition" mode="out-in">
            <circle-badge v-if="materialCheck && showMaterialCheck" :key="'check-' + id" variant="primary" icon="check" class="badge--check"></circle-badge>
            <circle-badge v-else-if="!materialCheck" :key="'error-' + id" variant="exception" icon="exclamation-mark"></circle-badge>
          </transition>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--clickable edit-calculation-list-header-cell--copyable"
           @click="action($event,'price')">
        <div class="bulk-edit-row__data">
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <ph-tag size="16"/>
            {{ toFixed(premise.material_cost, '€') }}
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <ph-chart-pie-slice size="16"/>
            {{ toPercent(premise.oversea_share) }}
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub" v-if="premise.is_fca_enabled">
            <basic-badge icon="plus" size="compact" variant="primary">FCA</basic-badge>
          </div>
        </div>
        <div class="bulk-edit-row__status">
          <transition name="badge-transition" mode="out-in">
            <circle-badge v-if="priceCheck && showPriceCheck" :key="'check-price-' + id" variant="primary"
                          icon="check" class="badge--check"></circle-badge>
            <circle-badge v-else-if="!priceCheck" :key="'error-price-' + id" variant="exception" icon="exclamation-mark"></circle-badge>
          </transition>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--clickable edit-calculation-list-header-cell--copyable"
           @click="action($event,'packaging')">
        <div class="bulk-edit-row__data">
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <PhVectorThree size="16"/>
            {{ toDimension(premise.handling_unit) }}
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <PhBarbell size="16"/>
            <span>{{ toFixed(premise.handling_unit.weight, premise.handling_unit.weight_unit, 0) }}</span>
          </div>
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <PhHash size="16"/>
            {{ toFixed(premise.handling_unit.content_unit_count, 'pcs.', 0) }}
          </div>
          <div class="bulk-edit-row__badges">
            <basic-badge v-if="premise.is_stackable" size="compact" variant="primary" icon="stack">STACKABLE
            </basic-badge>
            <basic-badge v-if="premise.is_mixable" size="compact" variant="secondary" icon="shuffle">MIXABLE
            </basic-badge>
          </div>
        </div>
        <div class="bulk-edit-row__status">
          <transition name="badge-transition" mode="out-in">
            <circle-badge v-if="packagingCheck && showPackagingCheck" :key="'check-packaging-' + id" variant="primary"
                          icon="check" class="badge--check"></circle-badge>
            <circle-badge v-else-if="!packagingCheck" :key="'error-packaging-' + id" variant="exception"
                          icon="exclamation-mark"></circle-badge>
          </transition>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--filterable"
           @click="action($event,'supplier')"
           @mousedown="handleMouseDown">
        <div class="bulk-edit-row__data">
          <div class="bulk-edit-row__line bulk-edit-row__line--sub">
            <ph-factory style="display: inline-block; vertical-align: middle;" size="16"/>
            {{ premise.supplier.name }}
          </div>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div
          class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--clickable bulk-edit-row__cell--destinations"
          @click="action($event,'amount')">
        <div class="bulk-edit-row__data bulk-edit-row__data--destinations">
          <div class="bulk-edit-row__dest-line"
               v-for="(destination, index) in destinations.slice(0, 3)"
               :key="index">
            <div>
              <ph-stack size="16"/>
            </div>
            <div>{{ toFixed(destination.annual_amount, 'pcs.', 0) }}</div>
            <div>
              <basic-badge size="compact" variant="secondary">{{ toDestination(destination) }}</basic-badge>
            </div>
          </div>
          <div class="bulk-edit-row__dest-line" v-if="destinations.length > 3">
            <div></div>
            <div> more ...</div>
            <div></div>
          </div>
        </div>

        <!-- Expanded destinations overlay -->
        <div class="bulk-edit-row__destinations-expanded" v-if="destinations.length > 3">
          <div class="bulk-edit-row__dest-line"
               v-for="(destination, index) in destinations"
               :key="index">
            <div>
              <ph-stack size="16"/>
            </div>
            <div>{{ toFixed(destination.annual_amount, 'pcs.', 0) }}</div>
            <div>
              <basic-badge size="compact" variant="secondary">{{ toDestination(destination) }}</basic-badge>
            </div>
          </div>
        </div>

        <div class="bulk-edit-row__status">
          <transition name="badge-transition" mode="out-in">
            <circle-badge v-if="destinationCheck && showDestinationCheck" :key="'check-dest-' + id" variant="primary"
                          icon="check" class="badge--check"></circle-badge>
            <circle-badge v-else-if="!destinationCheck" :key="'error-dest-' + id" variant="exception" icon="exclamation-mark"></circle-badge>
          </transition>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__cell-container">
      <div
          class="bulk-edit-row__cell bulk-edit-row__cell--status bulk-edit-row__cell--clickable bulk-edit-row__cell--destinations"
          @click="action($event,'routes')">
        <div class="bulk-edit-row__data">
          <div class="bulk-edit-row__route-line"
               v-for="(destination, index) in destinations.slice(0, 3)"
               :key="index">
            <div>
              <component :is="toRouteIcon(destination)" size="16"></component>
            </div>
            <div>{{ toRoute(destination) }}</div>
            <div>
              <basic-badge size="compact" variant="secondary">{{ toDestination(destination) }}</basic-badge>
            </div>
          </div>
          <div class="bulk-edit-row__route-line" v-if="destinations.length > 3">
            <div></div>
            <div> more ...</div>
            <div></div>
          </div>
        </div>

        <!-- Expanded destinations overlay -->
        <div class="bulk-edit-row__destinations-expanded" v-if="destinations.length > 3">
          <div class="bulk-edit-row__route-line"
               v-for="(destination, index) in destinations"
               :key="index">
            <div>
              <component :is="toRouteIcon(destination)" size="16"></component>
            </div>
            <div>{{ toRoute(destination) }}</div>
            <div>
              <basic-badge size="compact" variant="secondary">{{ toDestination(destination, 15) }}</basic-badge>
            </div>
          </div>
        </div>

        <div class="bulk-edit-row__status">
          <transition name="badge-transition" mode="out-in">
            <circle-badge v-if="routeCheck && showRouteCheck" :key="'check-route-' + id" variant="primary"
                          icon="check" class="badge--check"></circle-badge>
            <circle-badge v-else-if="!routeCheck" :key="'error-route-' + id" variant="exception" icon="exclamation-mark"></circle-badge>
          </transition>
        </div>
      </div>
    </div>

    <div class="bulk-edit-row__actions">
      <icon-button icon="pencil-simple" help-text="Edit this calculation" help-text-position="left"
                   @click="editSingle"></icon-button>
      <icon-button icon="x" help-text="Remove from mass edit" help-text-position="left" @click="remove"></icon-button>
    </div>
  </div>
</template>

<script>
import Checkbox from "@/components/UI/Checkbox.vue";
import IconButton from "@/components/UI/IconButton.vue";
import {mapStores} from "pinia";
import {usePremiseEditStore} from "@/store/premiseEdit.js";
import BasicBadge from "@/components/UI/BasicBadge.vue";
import {
  PhBarbell, PhBoat,
  PhChartPieSlice,
  PhFactory,
  PhHandCoins,
  PhHash,
  PhMapPinLine,
  PhPackage, PhPath,
  PhTag, PhTrain, PhTruck,
  PhVectorThree
} from "@phosphor-icons/vue";
import {UrlSafeBase64} from "@/common.js";
import CircleBadge from "@/components/UI/CircleBadge.vue";
import {useDestinationEditStore} from "@/store/destinationEdit.js";

export default {
  name: "BulkEditRow",
  emits: ['remove', 'action', 'select'],
  components: {
    PhPath,
    PhMapPinLine,
    PhPackage,
    PhTag,
    PhChartPieSlice,
    PhHandCoins,
    CircleBadge,
    PhFactory,
    PhBarbell,
    PhHash,
    PhVectorThree,
    BasicBadge,
    IconButton,
    Checkbox
  },
  props: {
    id: {
      type: Number,
      required: true
    },
    premise: {
      type: Object,
      required: true,
    }
  },
  data() {
    return {
      // Flags to show check badges only on transition
      showMaterialCheck: false,
      showPriceCheck: false,
      showPackagingCheck: false,
      showDestinationCheck: false,
      showRouteCheck: false,
      // Flag to track if component has been initialized
      isInitialized: false,
      // Store the initial state to prevent false triggers on mount
      initialCheckStates: null,
    }
  },
  computed: {
    materialCheck() {
      return (this.premise?.material.part_number != null && this.premise?.hs_code != null && this.premise?.tariff_rate != null)
    },
    priceCheck() {
      return (this.premise?.material_cost != null && this.premise?.oversea_share != null);
    },
    hu() {
      return this.premise.handling_unit;
    },
    packagingCheck() {
      return this.hu?.length != null
          && this.hu?.width != null
          && this.hu?.height != null
          && this.hu?.weight != null
          && this.hu?.content_unit_count != null;
    },
    destinationCheck() {

      if (((this.destinations ?? null) === null) || this.destinations.length === 0)
        return true;

      return !this.destinations?.some(d => d.annual_amount == null);

    },
    routeCheck() {

      if (((this.destinations ?? null) === null) || this.destinations.length === 0)
        return true;

      return this.destinations?.every(d => d.routes?.some((route) => route.is_selected));
    },
    isSelected() {
      return this.premiseEditStore.isChecked(this.id);
    },
    destinations() {
      return this.destinationEditStore.getByPremiseId(this.id) ?? [];
    },
    ...mapStores(usePremiseEditStore, useDestinationEditStore),
  },
  watch: {
    materialCheck(newVal, oldVal) {
      if (this.isInitialized
          && oldVal === false
          && newVal === true
          && this.initialCheckStates?.material !== true) {
        this.showMaterialCheck = true;
        // Reset initial state after first valid transition
        if (this.initialCheckStates) {
          this.initialCheckStates.material = true;
        }
      }
    },
    priceCheck(newVal, oldVal) {
      if (this.isInitialized
          && oldVal === false
          && newVal === true
          && this.initialCheckStates?.price !== true) {
        this.showPriceCheck = true;
        if (this.initialCheckStates) {
          this.initialCheckStates.price = true;
        }
      }
    },
    packagingCheck(newVal, oldVal) {
      if (this.isInitialized
          && oldVal === false
          && newVal === true
          && this.initialCheckStates?.packaging !== true) {
        this.showPackagingCheck = true;
        if (this.initialCheckStates) {
          this.initialCheckStates.packaging = true;
        }
      }
    },
    destinationCheck(newVal, oldVal) {
      if (this.isInitialized
          && oldVal === false
          && newVal === true
          && this.initialCheckStates?.destination === false) { // Hier war !== true, sollte === false sein
        this.showDestinationCheck = true;
        if (this.initialCheckStates) {
          this.initialCheckStates.destination = true;
        }
      }
    },
    routeCheck(newVal, oldVal) {
      if (this.isInitialized
          && oldVal === false
          && newVal === true
          && this.initialCheckStates?.route === false) { // Hier war !== true, sollte === false sein
        this.showRouteCheck = true;
        if (this.initialCheckStates) {
          this.initialCheckStates.route = true;
        }
      }
    },
  },
  mounted() {
    // Capture initial states BEFORE setting isInitialized
    // This prevents the watchers from triggering on mount
    this.initialCheckStates = {
      material: this.materialCheck,
      price: this.priceCheck,
      packaging: this.packagingCheck,
      destination: this.destinationCheck,
      route: this.routeCheck,
    };

    this.$nextTick(() => {
      this.isInitialized = true;
    });
  },
  methods: {
    toDestination(destination, limit = 15) {
      return this.toNode(destination.destination_node, limit);
    },
    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)}`;

    },
    toDimension(handlingUnit) {
      if (((handlingUnit ?? null) == null)
          || ((handlingUnit.length ?? null) == null)
          || ((handlingUnit.width ?? null) == null)
          || ((handlingUnit.height ?? null) == null)
      ) return 'N/A';

      return `${this.toFixed(handlingUnit.length, null, 0)} x ${this.toFixed(handlingUnit.width, null, 0)} x ${this.toFixed(handlingUnit.height, null, 0)} ${handlingUnit.dimension_unit}`;
    },
    toRoute(destination, limit = 32) {
      const route = destination?.routes?.find((route) => route.is_selected) ?? null;

      if (destination.is_d2d)
        return 'D2D Routing';

      if (!route)
        return 'N/A';

      const nodes = route.transit_nodes?.map((node) => this.toNode(node)) ?? [];

      if (nodes.length === 0)
        return 'N/A';

      const separator = " > ";
      let fullString = nodes.join(separator);

      if (fullString.length <= limit)
        return fullString;

      const front = nodes[0].concat(separator).concat("...").concat(separator);
      let back = [];

      for (const node of nodes.slice().reverse()) {

        back.unshift(node);
        const temp = front.concat(back.join(separator));

        if (temp.length > limit) {
          return front.concat(back.slice(1).join(separator));
        }

      }
    },
    toRouteIcon(destination) {
      const route = destination?.routes?.find((route) => route.is_selected) ?? null;

      if (destination.is_d2d)
        return 'PhShippingContainer';

      if (route?.type === 'SEA')
        return 'PhBoat';

      if (route?.type === 'RAIL')
        return 'PhTrain';

      if (route?.type === 'ROAD')
        return 'PhTruck';


      return 'PhEmpty';
    },
    toFixed(value, unit = null, decimals = 2) {
      return value !== null ? `${(value).toFixed(decimals)} ${unit ?? ''}` : 'N/A';
    },
    toPercent(value) {
      return value !== null ? `${(value * 100).toFixed(2)} %` : 'N/A';
    },
    editSingle() {
      const bulkQuery = this.$route.params.ids;
      const urlStr = new UrlSafeBase64().encodeIds([this.id]);
      this.$router.push({name: 'bulk-single-edit', params: {id: urlStr, ids: bulkQuery}});
    },
    handleMouseDown(event) {
      if (event.shiftKey || event.ctrlKey) {
        event.preventDefault();
      }
    },
    handleWheel(event) {
      if (event.ctrlKey) {
        event.preventDefault();
        window.scrollBy(0, event.deltaY);
      }
    },
    action(event, action) {

      if (event.ctrlKey && !event.shiftKey && (action === 'material' || action === 'supplier')) {
        this.$emit('action', {id: this.id, action: action.concat('-filter')});
      } else if (event.ctrlKey && event.shiftKey && (action === 'material' || action === 'supplier')) {
        this.$emit('action', {id: this.id, action: action.concat('-append')});
      } else if (action !== 'supplier') {
        this.$emit('action', {id: this.id, action: action});
      }

    },
    updateSelected(value) {
      this.$emit("select", {id: this.id, checked: value});
    },
    remove() {
      this.premiseEditStore.removePremise(this.id);
      this.$emit('remove', this.id);
    }
  }
}
</script>

<style scoped>
/* Main container */
.bulk-edit-row {
  display: grid;
  grid-template-columns: 6rem 0.8fr 0.7fr 1fr 1fr 1.2fr 2fr 10rem;
  gap: 1.6rem;
  padding: 0 2.4rem;
  border-bottom: 0.16rem solid #f3f4f6;
  align-items: stretch;
  transition: background-color 0.2s ease;
  font-size: 1.2rem;
  font-weight: 500;
  height: 14rem;
  overflow: visible;
  position: relative;
  z-index: 1;
}

.bulk-edit-row:last-child {
  border-bottom: none;
}

/* Erhöhe z-index der gesamten Row beim Hover über destinations */
.bulk-edit-row:has(.bulk-edit-row__destinations-expanded:hover) {
  z-index: 50;
}

/* Checkbox cell */
.bulk-edit-row__checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Cell container */
.bulk-edit-row__cell-container {
  display: flex;
  flex-direction: column;
  align-self: stretch;
  justify-content: center;
}

/* Cell */
.bulk-edit-row__cell {
  flex: 1 1 auto;
  margin: 1.6rem 0;
  padding: 0.8rem;
  border-radius: 0.8rem;
}

.bulk-edit-row__cell--status {
  display: flex;
  flex-direction: row;
  gap: 0.8rem;
}

.bulk-edit-row__cell--clickable:hover {
  cursor: pointer;
  background-color: #f8fafc;
}


.bulk-edit-row__cell--destinations {
  position: relative;
}

/* Cell data */
.bulk-edit-row__data {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  flex: 1;
}

.bulk-edit-row__data--destinations {
  position: relative;
  z-index: 1;
}

/* Cell status */
.bulk-edit-row__status {
  display: flex;
  align-items: center;
  flex: 0 0 auto;
}

/* Badge Transition Animation */
.badge-transition-enter-active {
  animation: badge-enter 0.3s ease-in both;
}

.badge-transition-leave-active {
  animation: badge-leave 0.3s ease-in;
}

/* Check badge fade-out Animation - wird NACH der Enter-Animation ausgeführt */
.badge--check {
  animation: badge-enter 0.3s ease-out 0.1s both,
  badge-zoom-fade-out 0.6s ease-out both;
}

@keyframes badge-enter {
  0% {
    transform: scale(1);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes badge-leave {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(0.8);
    opacity: 0;
  }
}

@keyframes badge-zoom-fade-out {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  30% {
    transform: scale(3);
    opacity: 1;
  }
  100% {
    transform: scale(0.5);
    opacity: 0;
  }
}

/* Lines */
.bulk-edit-row__line {
  display: flex;
  align-items: flex-start;
  gap: 0.8rem;
}

.bulk-edit-row__line--sub {
  font-size: 1.2rem;
  font-weight: 400;
  color: #6b7280;
}

/* Destination lines */
.bulk-edit-row__dest-line {
  display: grid;
  grid-template-columns: auto 1fr 2fr;
  gap: 0.4rem;
  font-size: 1.2rem;
  font-weight: 400;
  color: #6b7280;
}

/* Destination lines */
.bulk-edit-row__route-line {
  display: grid;
  grid-template-columns: auto 2fr 1fr;
  gap: 0.4rem;
  font-size: 1.2rem;
  font-weight: 400;
  color: #6b7280;
}

/* Badges */
.bulk-edit-row__badges {
  display: flex;
  gap: 0.8rem;
}

.bulk-edit-row__warning-badge {
  position: absolute;
  top: 0.8rem;
  right: 0.8rem;
  z-index: 1;
}

/* Expanded destinations overlay */
.bulk-edit-row__destinations-expanded {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: white;
  border: 0.1rem solid #E3EDFF;
  border-radius: 0.8rem;
  box-shadow: 0 0.4rem 0.6rem rgba(0, 0, 0, 0.1);
  padding: 0.8rem;
  z-index: 100;
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  opacity: 0;
  transform: translateY(-0.4rem);
  pointer-events: none;
  transition: opacity 0.2s ease, transform 0.2s ease;
  max-height: 0;
  overflow: hidden;
}

.bulk-edit-row__cell--destinations:hover .bulk-edit-row__destinations-expanded {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
  max-height: 50rem;
}

.bulk-edit-row__cell--destinations:hover .bulk-edit-row__data--destinations {
  opacity: 0;
}

.bulk-edit-row__cell--destinations:not(:has(.bulk-edit-row__destinations-expanded)):hover .bulk-edit-row__data--destinations {
  opacity: 1;
}

/* Actions */
.bulk-edit-row__actions {
  display: flex;
  align-items: center;
  gap: 1.6rem;
}
</style>