<script setup>
import RestrictedPageWrapper from "@/components/page/wrappers/RestrictedPageWrapper.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import DepartmentDashboardPageWrapper from "@/views/dashboards/departmentDashboard/DepartmentDashboardPageWrapper.vue";
import NotFoundFallBackPageWrapper from "@/components/page/wrappers/NotFoundFallBackPageWrapper.vue";
import {ref} from 'vue';

const opening_hours = ref(null);

const isOpeningHoursLoaded = () => { return opening_hours.value !== null; }

const weekday_opening_hours = (start, end) => {
  return {
    start: start,
    end: end,
    active: function() {
      return this.start !== null && this.end !== null;
    },
  }
}

const generateWeekDay = (name, label, start = null, end = null) => {
  return {
    name: name,
    label: label,
    ...weekday_opening_hours(start, end),
  }
}

const weekdays = ref([
  generateWeekDay('monday', 'Mandag'),
  generateWeekDay('tuesday', 'Tirsdag'),
  generateWeekDay('wednesday', 'Onsdag'),
  generateWeekDay('thursday', 'Torsdag'),
  generateWeekDay('friday', 'Fredag'),
  generateWeekDay('saturday', 'Lørdag'),
  generateWeekDay('sunday', 'Søndag'),
]);

const onChangeTime = (name, value) => {
  console.log(name, value);
  let opening_hours_id = opening_hours.value.id;
  SessionUser.objects.department_time_bookings_opening_hours.set[name](opening_hours_id, value);
  // Set the value in the input field
  const element = document.getElementById(name);
  if (element) {
    element.value = value;
  }
  // Update the opening hours object
  opening_hours.value[name] = value;
}

const getControlClass = (weekday, type) => {
  return '';
}

const getOpeningHours = (departmentId) => {
  // Fetch the opening hours for the department
  SessionUser.request(
      SessionUser.objects.department_time_bookings_opening_hours.meta.endpoint,
      'GET',
      {
        department: departmentId
      }
  ).then((response) => {
    console.log('response', response.data.data);
    // Check if there's any object in the response
    opening_hours.value = response.data.data;
  })
  .catch((error) => {
    console.error('Error fetching opening hours:', error);
  });
}

const departmentId = SessionUser.functions.getDepartmentIdFromUrl();
if (departmentId) {
  getOpeningHours(departmentId);
} else {
  console.error('Department ID not found in URL');
}

const getOpeningHoursValue = (name) => {
  if (opening_hours.value === null) {
    return '';
  }
  return opening_hours.value[name];
}
</script>

<template>
  <RestrictedPageWrapper :hasPermission="SessionUser.canAccessAdmin()">
    <DepartmentDashboardPageWrapper
        :title="SessionUser.objects.global.language.opening_hours"
        subtitle="Afdelingens åbningstider"
    >
      <NotFoundFallBackPageWrapper :exists="SessionUser.functions.getDepartmentIdFromUrl() && SessionUser.canAccessDepartment(SessionUser.functions.getDepartmentIdFromUrl())" error="Please select a department, that you have access to. If you believe this is an error, please contact support.">
        <table class="table is-striped is-bordered is-hoverable is-fullwidth">
          <thead>
            <tr>
              <th>{{SessionUser.objects.global.language.weekday}}</th>
              <th>{{SessionUser.objects.global.language.opening_hour}}</th>
              <th>{{SessionUser.objects.global.language.closing_hour}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(weekday, index) in weekdays" :key="index">
              <td>{{ weekday.label }}</td>
              <td>
                <div class="field has-addons">
                <div class="control is-expanded" :class="getControlClass(weekday, 'start')">
                  <input type="time" class="input is-fullwidth" @change="onChangeTime(weekday.name + '_start', $event.target.value)" v-if="isOpeningHoursLoaded()" :value="getOpeningHoursValue(weekday.name + '_start')" :id="weekday.name + '_start'" />
                  <input type="time" class="input is-skeleton is-fullwidth" v-else disabled/>
                </div>
                  <!-- Delete button -->
                  <div class="control">
                    <button class="button is-danger" @click="onChangeTime(weekday.name + '_start', null)" v-bind:disabled="!getOpeningHoursValue(weekday.name + '_start')">
                      <span class="icon is-small">
                        <i class="fas fa-trash"></i>
                      </span>
                    </button>
                  </div>
                </div>
              </td>
              <td>
                <div class="field has-addons">
                  <div class="control is-expanded" :class="getControlClass(weekday, 'end')">
                    <input type="time" class="input is-fullwidth" @change="onChangeTime(weekday.name + '_end', $event.target.value)" v-if="isOpeningHoursLoaded()" :value="getOpeningHoursValue(weekday.name + '_end')" :id="weekday.name + '_end'" />
                    <input type="time" class="input is-skeleton is-fullwidth" v-else disabled/>
                  </div>
                  <!-- Delete button -->
                  <div class="control">
                    <button class="button is-danger" @click="onChangeTime(weekday.name + '_end', null)" v-bind:disabled="!getOpeningHoursValue(weekday.name + '_end')">
                      <span class="icon is-small">
                        <i class="fas fa-trash"></i>
                      </span>
                    </button>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </NotFoundFallBackPageWrapper>
    </DepartmentDashboardPageWrapper>
  </RestrictedPageWrapper>
</template>

<style scoped>
</style>