<script setup>
import EditableTableColumn from "@/components/displays/buttons/EditableTableColumn.vue";

const props = defineProps({
  vehicles: {
    type: Array,
    required: true,
  },
  show_add_vehicle: {
    type: Number,
    required: false,
    default: true,
  },
  compact: {
    type: Boolean,
    required: false,
    default: false,
  },
  reloadList: {
    type: Function,
    required: false,
    default: null
  },
  add_other_customer_id: {
    type: Number,
    required: false,
    default: null
  }
});
import { ref, defineEmits } from 'vue';
import { departments, getDepartments, isLoading, getDepartmentName} from "@/components/pagination/departmentTabs.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { loadList } from "@/components/pagination/paginatedList.vue";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";


const reload = () => {
  // Load the list of vehicles
  if (props.reloadList) {
    props.reloadList();
  } else {
    loadList();
  }
};

const redirectUserVehiclePage = (vehicleId) => {
  // Send the user to the vehicle page
  window.location.href = `/user/vehicles/${vehicleId}`;
};

// Get the departments (If the departments are not already loaded)
if (departments.value.length === 0) {
  getDepartments();
}

// If the screen is mobile, set the is small variable to true
const isSmall = ref(window.innerWidth < 1024);

// When the window is resized, check if the screen is mobile
window.addEventListener('resize', () => {
  isSmall.value = window.innerWidth < 1024;
});

const onClickListAddons = (vehicleId) => {
  // Redirect to the product addons page
  console.log("Fetching product addons for vehicle: " + vehicleId);
  SessionUser.request(
      '/vehicles/addons/available',
      'GET',
      {
        id: vehicleId
      },
  )
};

const vehicleAddons = ref(null);
const getVehicleAvailableAddons = (vehicleId, forceReload = false) => {
  if (forceReload === true) {
    vehicleAddons.value = null;
  }
  // Get the vehicle addons from the server
  if (vehicleAddons.value === null) {
    vehicleAddons.value = [];
    SessionUser.request(
        '/vehicles/addons/available',
        'GET',
        {
          id: vehicleId
        },
    ).then((response) => {
      console.log("Vehicle addons: ", response.data.data);
      vehicleAddons.value = response.data.data;
    });
  }
  console.log("Vehicle addons: " + vehicleAddons.value);
  return vehicleAddons.value;
};

const toggleVehicleAddon = (vehicleId, addonId) => {
  // Toggle the vehicle addon
  SessionUser.request(
      '/vehicles/addons/toggle',
      'POST',
      {
        vehicle_id: vehicleId,
        addon_id: addonId
      },
  ).then(() => {
    reload();
  });
};

const getVehicleAddonToggleIcon = (vehicleAddon) => {
  // Check if the vehicle addon is applied
  if (isVehicleAddonApplied(vehicleAddon)) {
    return 'fas fa-minus';
  } else {
    return 'fas fa-plus';
  }
};

const isVehicleAddonApplied = (addon) => {
  if (!addon) {
    return false;
  }
  return addon.amount ? addon.amount > 0 : false;
};
</script>

<template>
  <div>
  <table class="table is-fullwidth" :class="isSmall ? 'is-hidden' : ''">
    <thead>
    <tr>
      <th v-if="!props.compact">ID</th>
      <th v-if="!props.compact">{{ SessionUser.objects.orders.columns.customer_id.label}}</th>
      <th>{{ SessionUser.objects.orders.columns.reg_1.label }}</th>
      <th>{{ SessionUser.objects.vehicles.columns.type.label }}</th>
      <th>{{ SessionUser.objects.vehicles.columns.wash_subscription.label }}</th>
      <th v-if="!props.compact">{{ SessionUser.objects.product_options.meta.title }}</th>
      <th v-if="!props.compact">{{ SessionUser.objects.vehicles.columns.reference.label }}</th>
      <th v-if="!props.compact">{{ SessionUser.objects.global.language.actions }}</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="object in props.vehicles" :key="object.id">
      <!-- ID -->
      <EditableTableColumn
          v-if="!props.compact"
          :object="object"
          :loadList="reload"
          column="id"
          />
      <!-- Customer ID -->
      <EditableTableColumn
          v-if="!props.compact"
          :object="object"
          :loadList="reload"
          column="customer_id"
          />
      <!-- Reg -->
      <EditableTableColumn
          :object="object"
          :loadList="reload"
          :editFunction="SessionUser.objects.vehicles.showEditObjectFieldForm"
          column="reg"
          />
      <!-- Type -->
      <EditableTableColumn
          :object="object"
          :loadList="reload"
          :editFunction="SessionUser.objects.vehicles.showEditObjectFieldForm"
          column="type"
          :parse-function="(value) => {
            return SessionUser.objects.products.functions.getProductName(value, 'Ukendt');
          }"
          />
      <!-- Wash Subscription -->
      <EditableTableColumn
          :object="object"
          :loadList="reload"
          :editFunction="SessionUser.objects.vehicles.showEditObjectFieldForm"
          column="wash_subscription"
          :parse-function="(value) => {
            return value ? SessionUser.objects.global.language.yes : SessionUser.objects.global.language.no;
          }"
          />
      <!-- Product Options, if the wash subscription is set to true -->
      <td v-if="!props.compact">
        <template v-if="object.wash_subscription">
          <!-- Enabled subscription -->
          <ActionSettingsWheelButton
            :label="SessionUser.objects.product_options.meta.title + (object.addons.enabled > 0 ? ' ( ' + object.addons.enabled + ' / ' + object.addons.available + ' )' : '')"
            :icon="SessionUser.objects.product_options.meta.icon"
            @mouseenter="getVehicleAvailableAddons(object.id, true)"
            >
            <template #actions>
              <!-- List addons -->
              <template v-for="vehicleAddon in vehicleAddons" :key="vehicleAddon.id">
                <ActionSettingsWheelItem
                  :label="(isVehicleAddonApplied(vehicleAddon) ? SessionUser.objects.global.language.remove : SessionUser.objects.global.language.add) + ' ' + vehicleAddon.name"
                  :icon="getVehicleAddonToggleIcon(vehicleAddon)"
                  :click-action="() => toggleVehicleAddon(object.id, vehicleAddon.id)"
                  :template="isVehicleAddonApplied(vehicleAddon) ? 'danger' : 'default'"
                />
              </template>
              <!-- If there are no addons, show a message -->
              <ActionSettingsWheelItem
                v-if="vehicleAddons ? vehicleAddons.length === 0 : true"
                :label="SessionUser.objects.global.language.no_data"
                icon="fas fa-list"
                />
              <!-- Addons -->
            </template>
          </ActionSettingsWheelButton>
        </template>
        <template v-else>
          <!-- Disabled subscription -->
          {{ SessionUser.objects.global.language.no_data }}
        </template>
      </td>
      <!-- Reference to the vehicle -->
      <EditableTableColumn
          v-if="!props.compact"
          :object="object"
          :loadList="reload"
          :editFunction="SessionUser.objects.vehicles.showEditObjectFieldForm"
          column="reference"
          />
      <!-- Actions -->
      <td>
        <!-- Actions -->
        <ActionSettingsWheelButton
            v-if="!props.compact"
            :user_id="object.user_id"
            :reg_1="object.reg"
        >
          <template #actions>
            <!-- Delete -->
            <ActionSettingsWheelItem
              :label="SessionUser.objects.global.language.delete + ' ' + SessionUser.objects.vehicles.meta.labels.single"
              icon="fas fa-trash"
              :template="'danger'"
              :click-action="() => SessionUser.objects.vehicles.functions.showDeleteObjectForm(object.id, () => reload())"
              />
          </template>
        </ActionSettingsWheelButton>
      </td>
    </tr>
    <!-- Add vehicle button -->
    <tr>
      <td colspan="10">
        <div class="buttons">
          <!-- Add own vehicle button (If the add_other_customer_id is not set) -->
          <button
              v-if="props.show_add_vehicle && !props.add_other_customer_id"
              class="button is-small is-text"
              @click="SessionUser.objects.vehicles.functions.showCreateObjectForCustomerForm(props.show_add_vehicle, () => reload())" style="text-decoration-line: none">
            Tilføj køretøj
          </button>
          <!-- Add other vehicle button -->
          <button
              v-if="props.add_other_customer_id"
              class="button is-small is-text"
              @click="SessionUser.objects.vehicles.functions.showCreateObjectForCustomerForm(props.add_other_customer_id, () => reload())" style="text-decoration-line: none">
            Tilføj køretøj til kunde
          </button>
        </div>
      </td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
      <td colspan="10">Showing {{ vehicles.length }} vehicles</td>
    </tr>
    </tfoot>
  </table>
  </div>
</template>

<style scoped>

</style>