<script setup>
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import {computed, defineEmits, defineProps, ref, watch} from "vue";
import ConfigurationSwitch from "@/components/displays/superuser/configuration/ConfigurationSwitch.vue";
import ShowErrorField from "@/components/global/ShowErrorField.vue";

const props = defineProps({
  timeBookingsNewProcess: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(['update:selected']);
const countryCodes = ref(null);
const onSelect = (value, automated = false) => {
  // Attempt to set the selected vehicle type
  props.timeBookingsNewProcess.vehicleType.value = value;
  emits('update:selected', value);
};
const vehicleTypes = ref([]);
// Fetch vehicle types from the session user object
SessionUser.objects.vehicles.columns.type.options(false).then(options => {
  console.log(options);
  function formatElement(option) {
    return {
      value: option.value || option.id,
      label: option.label || option.name,
      description: option.description || '',
      icon: option.icon || 'fas fa-car',
      price: option.price || 0,
      addons: option.addons || [],
    };
  }
  // Exclude the "Unknown" vehicle type (id: 0)
  options = options.filter(option => option.id !== 0);
  // Map the options to the desired format
  vehicleTypes.value = options.map(formatElement);
});

const getVehicleType = (id) => {
  return vehicleTypes.value.filter(vehicle => vehicle.value === parseInt(id))[0];
};

const departmentBookingTypes = ref([]);
// Fetch department booking types
const fetchDepartmentBookingTypes = () => {
  SessionUser.objects.department_time_bookings_types.get.single(props.timeBookingsNewProcess.department.value).then(options => {
    console.log('Department booking types:', options);
    // Map the options to the desired format
    departmentBookingTypes.value = options.map(option => ({
      ...getVehicleType(option.product),
      product: option.product,
      value: option.id,
      ...(option.name !== '' ? {label: option.name} : {}),
      ...(option.description !== '' ? {description: option.description} : {}),
      ...(option.duration ? {duration: option.duration} : {}),
    }));
    console.log('Mapped department booking types:', departmentBookingTypes.value);
  });
};
const getDepartmentBookingType = (id) => {
  return departmentBookingTypes.value.filter(type => type.value === parseInt(id))[0];
};


const applicableDepartmentBookingTypes = computed(() => {
  // Filter department booking types based on the selected vehicle type
  return departmentBookingTypes.value.filter(type => {
    const vehicleType = getVehicleType(props.timeBookingsNewProcess.vehicleType.value);
    return vehicleType && type.product === vehicleType.value;
  });
});

// Watch for changes in the vehicle type to update the vehicle type object
watch(() => props.timeBookingsNewProcess.vehicleType.value, (newValue) => {
  if (newValue !== null) {
    props.timeBookingsNewProcess.vehicleTypeObject.value = getVehicleType(newValue);
    // Select the first applicable department booking type if available
    const applicableType = applicableDepartmentBookingTypes.value[0] || null;
    props.timeBookingsNewProcess.setDepartmentBookingType(applicableType ? applicableType.value : null, applicableType);
  } else {
    props.timeBookingsNewProcess.vehicleTypeObject.value = null;
  }
});

// Watch for changes in the vehicleTypes array to update the vehicle type object
watch(vehicleTypes, (newVehicleTypes) => {
  if (props.timeBookingsNewProcess.vehicleType.value !== null) {
    props.timeBookingsNewProcess.vehicleTypeObject.value = getVehicleType(props.timeBookingsNewProcess.vehicleType.value);
  }
  // Fetch department booking types when the vehicle types are loaded
  fetchDepartmentBookingTypes();
});

// Watch for changes in the applicable department booking types to update the department booking type object
watch(applicableDepartmentBookingTypes, (newTypes) => {
  // If the current department booking type is not in the new types, reset it
  if (!newTypes.some(type => type.value === props.timeBookingsNewProcess.departmentBookingType.value)) {
    props.timeBookingsNewProcess.setDepartmentBookingType(null, null);
  }
  // If there are applicable types, set the first one as the default
  if (newTypes.length > 0 && props.timeBookingsNewProcess.departmentBookingType.value === null) {
    const firstType = newTypes[0];
    props.timeBookingsNewProcess.setDepartmentBookingType(firstType.value, firstType);
  }
});

// Watch for changes in the department to fetch applicable booking types
watch(() => props.timeBookingsNewProcess.department.value, (newDepartmentId) => {
  if (newDepartmentId) {
    fetchDepartmentBookingTypes();
  } else {
    departmentBookingTypes.value = [];
  }
});

const vehicleTypesWithDepartmentBookingTypes = computed(() => {
  // Filter out vehicle types that don't have a department booking type
  return vehicleTypes.value.filter(vehicle => {
    return departmentBookingTypes.value.some(type => type.product === vehicle.value);
  });
});

// Initialize the vehicle type object based on the current value
if (props.timeBookingsNewProcess.vehicleType.value !== null) {
  onSelect(props.timeBookingsNewProcess.vehicleType.value, true);
} else {
  props.timeBookingsNewProcess.vehicleTypeObject.value = null;
}
</script>

<template>
  <!-- Vehicle type select -->
  <div class="field">
    <label class="label">{{SessionUser.objects.global.language.select}} {{SessionUser.objects.vehicles.meta.labels.single.toLowerCase()}} </label>
    <ConfigurationSelect
        v-bind:options="vehicleTypesWithDepartmentBookingTypes"
        :display_as_buttons="false"
        v-bind:value="timeBookingsNewProcess.vehicleType.value"
        v-on:update:value="(value) => onSelect(value)"
        icon="fas fa-car"
    />
  </div>
  <!-- Department booking type select -->
  <div class="field" v-if="props.timeBookingsNewProcess.vehicleType.value !== null && getVehicleType(props.timeBookingsNewProcess.vehicleType.value)" v-show="(applicableDepartmentBookingTypes.length > 1)">
  <label class="label">{{SessionUser.objects.global.language.select}} {{SessionUser.objects.department_time_bookings_types.columns.product.label.toLowerCase()}}</label>
    <ConfigurationSelect
        v-bind:options="applicableDepartmentBookingTypes"
        :display_as_buttons="false"
        v-bind:value="props.timeBookingsNewProcess.departmentBookingType.value"
        v-on:update:value="(value) => props.timeBookingsNewProcess.setDepartmentBookingType(value, getDepartmentBookingType(value))"
        icon="fas fa-calendar-alt"
    />
  </div>
  <!-- If there is no applicable department booking type, show a message -->
  <div class="field" v-if="props.timeBookingsNewProcess.vehicleType.value !== null && getVehicleType(props.timeBookingsNewProcess.vehicleType.value) && applicableDepartmentBookingTypes.length === 0">
    <show-error-field message="Der er ingen tilgængelige bookingtyper for den valgte køretøjstype i denne afdeling." />
  </div>
  <!-- Related service select -->
  <div class="field" v-if="props.timeBookingsNewProcess.vehicleType.value !== null && getVehicleType(props.timeBookingsNewProcess.vehicleType.value) && getVehicleType(props.timeBookingsNewProcess.vehicleType.value).addons.length > 0">
    <label class="label">{{SessionUser.objects.global.language.select}} {{SessionUser.objects.global.language.related_service.toLowerCase()}}</label>
    <template v-for="addon in getVehicleType(props.timeBookingsNewProcess.vehicleType.value).addons">
      <ConfigurationSwitch
          v-bind:is-compact="true"
          v-bind:value="props.timeBookingsNewProcess.hasAddon(addon.option_id)"
          v-bind:on-switch="() => props.timeBookingsNewProcess.toggleAddon(addon.option_id, addon)"
          v-bind:title="addon.name"
          v-bind:description="addon.description"
          v-bind:price="addon.product.price"
        />
    </template>
  </div>
</template>

<style scoped>

</style>