<template>
  <div class="destination-edit-routes-container">
    <div v-if="showMassEditWarning" class="destination-edit-route-warning">
      <ph-warning size="18px"></ph-warning>
      Routing is deactivated during mass edit. Please select routes for each calculation separately.
    </div>

    <div class="destination-edit-routes">
      <div class="destination-edit-column-caption">Destination</div>
      <div class="destination-edit-column-data">{{ destination.destination_node.name }}</div>

      <div class="destination-edit-column-caption">
        <tooltip :text="tooltipAnnualAmount" position="right">Annual quantity</tooltip>
      </div>
      <div class="destination-edit-column-data">
        <div class="text-container">
          <input :value="annualAmount" @blur="validateAnnualAmount" class="input-field"
                 autocomplete="off"/>
        </div>
      </div>

      <div v-if="!showMassEditWarning" class="destination-edit-column-caption">Calculation model</div>
      <div v-if="!showMassEditWarning" class="destination-edit-column-data destination-edit-cell-routing">
        <radio-option name="model" value="routing" v-model="calculationModel">standard routing</radio-option>
        <radio-option name="model" value="d2d" v-model="calculationModel">individual rate</radio-option>
      </div>



      <!-- Single grid cell for caption that transitions content -->
      <div v-if="!showMassEditWarning" class="destination-edit-column-caption destination-edit-caption-top">

          <div v-if="showRoutes || showRouteWarning" key="routes" class="destination-edit-caption-top-elem">Routes</div>
          <div v-else key="rate" class="destination-edit-caption-top-elem">D2D Rate [EUR]</div>

      </div>

      <!-- Single grid cell for data that transitions content -->
      <div v-if="!showMassEditWarning" class="destination-edit-column-data destination-edit-routes-cell">

          <div v-if="showRoutes" key="routes" class="destination-edit-cell-routes">
            <destination-route v-for="route in destination.routes" :key="route.id" :route="route"
                               :selected="route.is_selected" @click="selectRoute(route.id)" :responsive="false"></destination-route>
          </div>
          <div v-else-if="showRouteWarning">
            <div class="destination-edit-route-warning">
              <ph-warning size="18px"></ph-warning>
              Unable to route from supplier to {{ this.destination.destination_node.name }}. Please use individual route or contact administrator.
            </div>
          </div>
          <div v-else key="rate" class="text-container">
            <input :value="rateD2d" @blur="validateRateD2d" class="input-field"
                   autocomplete="off"/>
          </div>

      </div>

      <div class="destination-edit-column-caption">

        <div v-if="!showMassEditWarning && !showRoutes && !showRouteWarning"> Lead time [days]</div>

      </div>
      <div  class="destination-edit-column-data">

        <div v-if="!showMassEditWarning && !showRoutes && !showRouteWarning" key="rate" class="text-container">
          <input :value="leadtimeD2d" @blur="validateLeadTimeD2d" class="input-field"
                 autocomplete="off"/>
        </div>

      </div>


    </div>
  </div>
</template>

<script>
import RadioOption from "@/components/UI/RadioOption.vue";
import DestinationRoute from "@/components/layout/edit/destination/DestinationRoute.vue";
import {mapStores} from "pinia";
import {parseNumberFromString} from "@/common.js";
import Tooltip from "@/components/UI/Tooltip.vue";
import {useDestinationSingleEditStore} from "@/store/destinationSingleEdit.js";
import logger from "@/logger.js";

export default {
  name: "DestinationEditRoutes",
  components: {Tooltip, DestinationRoute, RadioOption},
  methods: {
    selectRoute(id) {
      this.destination.routes.forEach(route => route.is_selected = route.id === id);
    },
    validateAnnualAmount(event) {
      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();

      this.annualAmount = validatedValue;
      event.target.value = stringified;
    },
    validateRateD2d(event) {

      const value = parseNumberFromString(event.target.value, 2);
      const validatedValue = Math.max(0, value);
      const stringified = validatedValue.toFixed(2);

      this.rateD2d = validatedValue;
      event.target.value = stringified;
    },
    validateLeadTimeD2d(event) {

      const value = parseNumberFromString(event.target.value, 0);
      const validatedValue = Math.max(0, value);
      const stringified = validatedValue.toFixed();

      this.leadtimeD2d = validatedValue;
      event.target.value = stringified;
    }
  },
  created() {
    logger.log("Destination:", this.destination)
  },
  data() {
    return {
      selectedCalculationModel: 'routing',
    }
  },
  computed: {
    tooltipAnnualAmount() {
      return `Annual quantity that "${this.destination.destination_node.name}" will source from the supplier`
    },
    showMassEditWarning() {
      return (this.destination.routes ?? null) === null;
    },
    showRoutes() {
      return !this.destination.is_d2d && (this.destination.routes?.length > 0);
    },
    showRouteWarning() {
      return !this.destination.is_d2d && this.destination.routes?.length === 0;
    },
    calculationModel: {
      get() {
        if (this.destination.is_d2d) {
          return 'd2d';
        } else {
          return 'routing';
        }
      },
      set(value) {
        this.destination.is_d2d = value === 'd2d';
      }
    },
    ...mapStores(useDestinationSingleEditStore),
    destination() {
      return this.destinationSingleEditStore.destination;
    },
    annualAmount: {
      get() {
        return this.destination.annual_amount?.toFixed() ?? '';
      },
      set(value) {
        this.destination && (this.destination.annual_amount = value);
      },
    },
    rateD2d: {
      get() {
        return this.destination.rate_d2d?.toFixed(2) ?? '0.00';
      },
      set(value) {
        this.destination && (this.destination.rate_d2d = value);
      }
    },
    leadtimeD2d: {
      get() {
        return this.destination.lead_time_d2d?.toFixed() ?? '0';
      },
      set(value) {
        this.destination && (this.destination.lead_time_d2d = value);
      }
    }
  }
}
</script>

<style scoped>
/* Smooth fade transition */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.25s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.destination-edit-routes-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0; /* Important for flexbox shrinking */
  margin: 1.6rem;
}

.destination-edit-route-warning {
  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-bottom: 1.6rem;
}

.destination-edit-cell-routing {
  display: flex;
  flex-direction: row;
  gap: 1.6rem;
}

.destination-edit-routes {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: repeat(5, auto) 1fr; /* Last row takes remaining space */
  gap: 1.6rem;
  height: 100%;
  min-height: 0; /* Important for grid to shrink */
}

.destination-edit-column-data {
  align-self: center;
  font-weight: 300;
  font-size: 1.4rem;
  color: #6b7280;
}

.destination-edit-routes-cell {
  /* This cell needs to handle overflow */
  min-height: 0;
  align-self: stretch; /* Take full height of grid row */
}

.destination-edit-column-caption {
  font-size: 1.4rem;
  font-weight: 500;
  align-self: center;
  justify-self: end;
  color: #001D33;
  text-wrap: nowrap;
}

.destination-edit-caption-top {
  align-self: start; /* Align to top instead of center */
  display: flex;
  gap: 1.6rem;
}

.destination-edit-caption-top-elem {
  margin-top: 0.8rem;
}

.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 fit-content(80rem);
}

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

.destination-edit-cell-routes {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
  overflow-y: auto; /* Enable scrolling */
  height: 100%;
  min-height: 0;
  padding-right: 0.8rem; /* Space for scrollbar */
}
</style>