<script setup>
import FullCalendar from "@fullcalendar/vue3"
import resourceTimelinePlugin from '@fullcalendar/resource-timeline'
import deLocale from '@fullcalendar/core/locales/de'
import interactionPlugin from '@fullcalendar/interaction'
import listPlugin from '@fullcalendar/list';
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

const viewport = useViewport()

watch(viewport.breakpoint, (newBreakpoint, oldBreakpoint) => {
  console.log('Breakpoint updated:', oldBreakpoint, '->', newBreakpoint)
})

const supabase = useSupabaseClient()
const dataStore = useDataStore()
const resources = dataStore.getResources
const eventTypes = dataStore.getEventTypes
const events = dataStore.getEvents

const openNewEventModal = ref(false)
const showEventModal = ref(false)
const newEventData = ref({
  resourceId: "",
  resourceType: "",
  title: "",
  type: "Umsetzung",
  start: "",
  end: null
})

const selectedEvent = ref({})

const createEvent = async () => {
  const {data,error} = await supabase
      .from("events")
      .insert([newEventData.value])
      .select()

  if(error) {
    console.log(error)
  }

  console.log("OK")
  openNewEventModal.value = false
  newEventData.value = {}
  dataStore.fetchEvents()


}
const calendarOptionsList = reactive({
  locale: deLocale,
  plugins: [listPlugin],
  initialView: "listWeek",
  initialEvents: events,
  nowIndicator: true,
  height: "80vh"
})

const calendarOptionsTimeline = reactive({
  schedulerLicenseKey: "CC-Attribution-NonCommercial-NoDerivatives",
  locale: deLocale,
  plugins: [resourceTimelinePlugin, interactionPlugin],
  initialView: "resourceTimeline3Hours",

  headerToolbar: {
    left: 'prev,next',
    center: 'title',
    right: 'resourceTimelineDay,resourceTimeline3Hours,resourceTimelineMonth'
  },
  initialEvents: events,
  selectable: true,
  weekNumbers: true,
  select: function (info) {
    //console.log(info)
    newEventData.value.resourceId = info.resource.id
    if(info.resource.extendedProps){
      newEventData.value.resourceType = info.resource.extendedProps.type
    }

    newEventData.value.start = info.startStr
    newEventData.value.end = info.endStr
    openNewEventModal.value = true
  },
  eventClick: function (info){
    selectedEvent.value = info.event
    showEventModal.value = true

    console.log(info)
  },
  resourceGroupField: "type",
  resources: resources,
  nowIndicator:true,
  views: {
    resourceTimeline3Hours: {
      type: 'resourceTimeline',
      slotDuration: {hours: 3},
      slotMinTime: "06:00:00",
      slotMaxTime: "21:00:00",
      duration: {days:7},
      buttonText: "Woche",
      visibleRange: function(currentDate) {
        // Generate a new date for manipulating in the next step
        var startDate = new Date(currentDate);
        var endDate = new Date(currentDate);

        // Adjust the start & end dates, respectively
        startDate.setDate(startDate.getDate() - startDate.getDay() +1); // One day in the past
        endDate.setDate(startDate.getDate() + 5); // Two days into the future

        return { start: startDate, end: endDate };
      }
    }
  },

})

</script>

<template>
  <UDashboardPage>
    <UDashboardPanel grow>
      <UDashboardNavbar :title="currentItem ? currentItem.name : ''">
        <template #right>

        </template>
      </UDashboardNavbar>
      <div v-if="viewport.isLessThan('tablet')">
        <FullCalendar
            :options="calendarOptionsList"
        />
      </div>
      <div v-else>
        <FullCalendar
            :options="calendarOptionsTimeline"
        />
      </div>
    </UDashboardPanel>
  </UDashboardPage>



  <div>
    <UModal
      v-model="openNewEventModal"
    >
      <UCard>
        <template #header>
          Neuen Termin erstellen
        </template>

        <UFormGroup
          label="Resource:"
        >
          <USelectMenu
            v-model="newEventData.resourceId"
            :options="resources"
            value-attribute="id"
            option-attribute="title"
          >
            <template #label>
              <span>{{ resources.find(resource => resource.id === newEventData.resourceId).title }}</span>
            </template>
          </USelectMenu>
        </UFormGroup>
        <UFormGroup
          label="Titel:"
        >
          <UInput
            v-model="newEventData.title"
          />
        </UFormGroup>
        <UFormGroup
          label="Projekt:"
        >
          <USelectMenu
            v-model="newEventData.project"
            :options="dataStore.projects"
            option-attribute="name"
            value-attribute="id"
            searchable
            searchable-placeholder="Suche..."
            :search-attributes="['name']"
          >
            <template #label>
              {{dataStore.getProjectById(newEventData.project) ? dataStore.getProjectById(newEventData.project).name : "Kein Projekt ausgewählt"}}
            </template>

          </USelectMenu>
        </UFormGroup>
        <UFormGroup
          label="Typ:"
        >
          <USelectMenu
            v-model="newEventData.type"
            :options="eventTypes"
            option-attribute="label"
            value-attribute="label"
          >

          </USelectMenu>
        </UFormGroup>
        <UFormGroup
          label="Start:"
        >
          <UInput
              v-model="newEventData.start"
          />
        </UFormGroup>
        <UFormGroup
          label="Ende:"
        >
          <UInput
              v-model="newEventData.end"
          />
        </UFormGroup>

        <template #footer>
          <UButton
            @click="createEvent"
          >
            Erstellen
          </UButton>
        </template>

      </UCard>
    </UModal>
    <UModal
      v-model="showEventModal"
    >
      <UCard>
        <template #header>
          {{selectedEvent.title}}
        </template>

        Start: {{dayjs(selectedEvent.startStr).format("DD.MM.YYYY HH:mm")}}<br>
        Ende: {{dayjs(selectedEvent.endStr).format("DD.MM.YYYY HH:mm")}}

        <DevOnly>
          <UDivider class="my-3"/>
          {{selectedEvent}}
        </DevOnly>



      </UCard>


    </UModal>



  </div>
</template>

<style scoped>

</style>