<script setup>
import deLocale from "@fullcalendar/core/locales/de";
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid"
import timeGridPlugin from "@fullcalendar/timegrid"
import resourceTimelinePlugin from "@fullcalendar/resource-timeline";
import interactionPlugin from "@fullcalendar/interaction";
import dayjs from "dayjs";

//Config
const route = useRoute()
const mode = ref(route.params.mode || "grid")
const supabase = useSupabaseClient()
const dataStore = useDataStore()
const resources = dataStore.getResources
const eventTypes = dataStore.getEventTypes


//Working
const newEventData = ref({
  resources: [],
  resourceId: "",
  resourceType: "",
  title: "",
  type: "Umsetzung",
  start: "",
  end: null
})
const showNewEventModal = ref(false)
const showEventModal = ref(false)
const selectedEvent = ref({})
const selectedResources = ref([])


//Functions
const convertResourceIds = () => {

  newEventData.value.resources = selectedResources.value.map(i => {
    /*if(i.type !== 'Mitarbeiter') {
      return {id: Number(i.id.split('-')[1]), type: i.type}
    } else {
      return {id: i.id, type: i.type}
    }*/

    if((String(i).match(/-/g) || []).length > 1) {
      return {type: "Mitarbeiter", id: i}
    } else {

      if(i.split('-')[0] === 'I') {
        return {id: Number(i.split('-')[1]), type: "Inventar"}
      } else if(i.split('-')[0] === 'F') {
        return {id: Number(i.split('-')[1]), type: "Fahrzeug"}
      }
    }


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

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

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


}

//Calendar Config
const calendarOptionsGrid = reactive({
  locale: deLocale,
  plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin],
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: 'dayGridMonth,timeGridWeek,timeGridDay'
  },
  initialView: "dayGridMonth",
  initialEvents: dataStore.getEvents,
  nowIndicator: true,
  height: "80vh",
  selectable: 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
    showNewEventModal.value = true
  },
  eventClick: function (info){
    selectedEvent.value = info.event
    showEventModal.value = true
  },
})

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: dataStore.getEventsByResource,
  selectable: true,
  select: function (info) {
    /*let resourceObj = {}

    resourceObj.id = info.resource.id
    if(info.resource.extendedProps){
      resourceObj.type = info.resource.extendedProps.type
    }

    console.log(resourceObj)*/

    selectedResources.value = [info.resource.id]
    newEventData.value.start = info.startStr
    newEventData.value.end = info.endStr
    console.log(newEventData.value)
    convertResourceIds()
    showNewEventModal.value = true
  },
  eventClick: function (info){
    selectedEvent.value = info.event
    showEventModal.value = true
  },
  resourceGroupField: "type",
  resourceOrder: "-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 };
      }
    }
  },
  height: '80vh',
})

</script>

<template>
  <!-- NEW EVENT MODAL  -->
  <UModal
      v-model="showNewEventModal"
  >
    <UCard>
      <template #header>
        Neuen Termin erstellen
      </template>
      <UFormGroup
          label="Resource:"
      >
        <USelectMenu
            v-model="selectedResources"
            :options="resources"
            option-attribute="title"
            value-attribute="id"
            multiple
            @change="convertResourceIds"
        >
          <template #label>
            <span v-if="selectedResources.length == 0">Keine Ressourcen ausgewählt</span>
            <span v-else >{{ selectedResources.length }} ausgewählt</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>

  <!--SHOW EVENT MODAL  -->
  <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 v-if="mode === 'grid'">
    <FullCalendar
        :options="calendarOptionsGrid"
    />
  </div>
  <div v-else-if="mode === 'timeline'">
    <FullCalendar
        :options="calendarOptionsTimeline"
    />
  </div>



</template>

<style scoped>

</style>