<script setup>
import {
  isLoaded,
  isLoading,
  list,
  loadList,
  metaCurrentPage,
  metaItemsPerPage,
  metaTotalItems,
  setEndpoint,
  setMetaItemsPerPage,
  setFilter,
  getFilter,
  setPage,
  search,
  metaSearch,
  setOrder,
  meta
} from "@/components/pagination/paginatedList.vue";
import { useRouter } from "vue-router";
import PaginationNavigation from "@/components/displays/pagination/PaginationNavigation.vue";

import LoadButtonWhileAwait from "@/components/request/LoadButtonWhileAwait.vue";
import PaginationDisplay from "@/components/displays/pagination/PaginationDisplay.vue";
import BookingsTable from "@/components/displays/user/bookings/bookingsTable.vue";
import {departments} from "@/components/pagination/departmentTabs.vue";
import {ref, watch} from "vue";
import { Colors } from "@/ThemeConfig.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const router = useRouter();

// Set the selected status to all
const selectedStatus = ref("*");
const selectedStatusPending = ref(false);

// Watch the selected status and set the filter
watch(selectedStatus, (value) => {
  setFilter("status", value);
  selectedStatusPending.value = value === "pending";
});

// Watch the selected status and set the filter
watch(() => getFilter("status"), (value) => {
  selectedStatus.value = value;
  selectedStatusPending.value = value === "pending";
});


// If the route starts with /user, set the endpoint to /user/bookings
if (router.currentRoute.value.path.startsWith("/user")) {
  setEndpoint("/user/bookings", false);
  setFilter("date", new Date().toISOString().split("T")[0], false);
  setOrder("created_at", "desc");
}
// If the route starts with /superuser, set the endpoint to /bookings
else if (router.currentRoute.value.path.startsWith("/superuser")) {
  setEndpoint("/bookings", true);
}
// If the route starts with /admin, set the endpoint to /bookings
else if (router.currentRoute.value.path.startsWith("/admin")) {
  setEndpoint("/bookings", false);
  setFilter("department", router.currentRoute.value.params.departmentId, false);
  // Default to only show pending (Unless the ?search query is set)
  if (!router.currentRoute.value.query.search)
  {
    setFilter("status", "pending", false);
    selectedStatus.value = "pending";
    selectedStatusPending.value = true;
  } else if (router.currentRoute.value.query.search) {
    search(router.currentRoute.value.query.search, false);
  }
} else {
  setEndpoint("/bookings", true);
}
setOrder("created_at", "desc");
loadList();

const showingToday = ref(true);

watch(() => getFilter("date"), (value) => {
  showingToday.value = value === new Date().toISOString().split("T")[0];
});

// 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;
});


</script>

<template>
  <input @input="search($event.target.value)" class="input mt-2" type="text" placeholder="Søg efter booking" v-model="metaSearch" />
  <PaginationDisplay :metaItemsPerPage="metaItemsPerPage" :loadFunction="loadList" :isLoading="isLoading" :setMetaItemsPerPage="setMetaItemsPerPage">
    <template #paginationColumns>
      <!-- Filter by status -->
      <div class="column is-narrow my-3">
        <label class="label">Status</label>
        <div class="control">
          <div class="select">
            <select @change="setFilter('status', $event.target.value)" v-model="selectedStatus">
              <option value="*">Alle</option>
              <option value="pending">Afventer</option>
              <option value="completed">Fuldført</option>
              <option value="cancelled">Annulleret</option>
            </select>
          </div>
        </div>
      </div>
      <!-- Filter by Pickup bool -->
      <div class="column is-narrow my-3">
        <label class="label">Afhentning</label>
        <div class="control">
          <div class="select">
            <select @change="setFilter('pickup_bool', $event.target.value)">
              <option value="*">Alle</option>
              <option value="1">Ja</option>
              <option value="0">Nej</option>
            </select>
          </div>
        </div>
      </div>
      <!-- Filter by department -->
      <div class="column is-narrow my-3" v-if="router.currentRoute.value.path.startsWith('/user')">
        <label class="label">Afdeling</label>
        <div class="control">
          <div class="select">
            <select @change="setFilter('department', $event.target.value)">
              <option value="*">Alle</option>
              <option v-for="department in departments" :key="department.id" :value="department.id">{{ department.name }}</option>
            </select>
          </div>
        </div>
      </div>
      <div class="column is-auto-fill my-3" v-if="!isSmall"/>
      <!-- Only show the bookings for today (Switch, if the route is /user) -->
      <div class="column is-narrow my-3" v-if="router.currentRoute.value.path.startsWith('/user')" :class="{ 'has-text-right': !isSmall }">
        <label class="label">{{ isSmall ? 'I dag' : 'Vis kun i dag' }}</label>
        <div class="control">
          <div class="field">
            <input id="today" type="checkbox" class="switch is-rounded" @change="(event) => { setFilter('date', event.target.checked ? new Date().toISOString().split('T')[0] : '*') }" checked="checked" :class="{ 'is-link': showingToday }" />
            <label for="today"></label>
          </div>
        </div>
      </div>
      <!-- Create a new booking, if the route is /user -->
      <div class="column is-narrow my-3" v-if="router.currentRoute.value.path.startsWith('/user')" :class="{ 'has-text-right': !isSmall }">
        <button
            class="button is-link"
            @click="SessionUser.functions.redirectTo.external('/user/bookings/new', true)"
            :style="{ 'color': Colors.buttons.textColor, 'background-color': Colors.buttons.backgroundColor }"
        >
          Ny booking
        </button>
      </div>
      <!-- Only show the pending bookings (Switch, if the route is /admin) -->
      <div class="column is-narrow my-3" v-if="router.currentRoute.value.path.startsWith('/admin')" :class="{ 'has-text-right': !isSmall }">
        <label class="label">{{ isSmall ? 'Afventende' : 'Vis kun afventende' }}</label>
        <div class="control">
          <div class="field">
            <input id="today" type="checkbox" class="switch is-rounded" @change="(event) => { setFilter('status', event.target.checked ? 'pending' : '*'); selectedStatus = event.target.checked ? 'pending' : '*'; }" :class="{ 'is-success': selectedStatus === 'pending' }" v-model="selectedStatusPending" />
            <label for="today"></label>
          </div>
        </div>
      </div>
    </template>
  </PaginationDisplay>
  <BookingsTable :objects="list" :meta="meta" class="mb-4" />
  <PaginationNavigation :currentPage="metaCurrentPage" :totalPages="Math.ceil(metaTotalItems / metaItemsPerPage)" :loadFunction="loadList" :setPage="setPage" :isLoading="isLoading" class="mt-3" />
  <LoadButtonWhileAwait class="is-dark" :isLoading="isLoading" :loadFunction="loadList" icon="fas fa-sync-alt">Opdater</LoadButtonWhileAwait>
</template>

<style scoped>

</style>