<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";
import { expandRecurringEvent } from "~/utils/eventRecurrence"

//TODO BACKEND CHANGE COLOR IN TENANT FOR RENDERING

//Config
const route = useRoute()
const router = useRouter()
const mode = ref(route.params.mode || "grid")
const dataStore = useDataStore()

const profileStore = useProfileStore()

//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([])

const events = ref([])
const sourceEvents = ref([])
const sourceAbsenceRequests = ref([])
const sourceProjects = ref([])
const sourceProfiles = ref([])
const sourceVehicles = ref([])
const sourceInventoryItems = ref([])
const sourceInventoryItemGroups = ref([])

const buildEventTitle = (event) => {
  if (event.name) return event.name
  if (event.project) {
    const project = sourceProjects.value.find((item) => item.id === event.project)
    return project?.name || ""
  }
  return ""
}

const buildEventColor = (event) =>
  profileStore.ownTenant.calendarConfig.eventTypes.find(type => type.label === event.eventtype)?.color || "black"

const expandEventsForRange = (rangeStart, rangeEnd) => {
  const gridEvents = sourceEvents.value.flatMap((event) =>
    expandRecurringEvent(event, rangeStart, rangeEnd, (occurrenceStart, occurrenceEnd, occurrenceIndex) => {
      const eventColor = buildEventColor(event)

      return {
        ...event,
        start: occurrenceStart.toISOString(),
        end: occurrenceEnd ? occurrenceEnd.toISOString() : null,
        title: buildEventTitle(event),
        borderColor: eventColor,
        textColor: eventColor,
        backgroundColor: "black",
        entrytype: "event",
        eventId: event.id,
        occurrenceIndex
      }
    })
  )

  const absenceEvents = sourceAbsenceRequests.value.map(absence => ({
    id: absence.id,
    resourceId: absence.user,
    resourceType: "person",
    title: `${absence.reason} - ${absence.profile.fullName}`,
    start: dayjs(absence.startDate).toDate(),
    end: dayjs(absence.endDate).add(1, 'day').toDate(),
    allDay: true,
    absencerequestId: absence.id,
    entrytype: "absencerequest",
  }))

  calendarOptionsGrid.value.initialEvents = [
    ...gridEvents,
    ...absenceEvents
  ]

  const timelineEvents = sourceEvents.value.flatMap((event) => {
    const eventColor = buildEventColor(event)
    const title = buildEventTitle(event)

    return expandRecurringEvent(event, rangeStart, rangeEnd, (occurrenceStart, occurrenceEnd) => {
      const returnData = {
        title,
        borderColor: eventColor,
        textColor: "white",
        backgroundColor: eventColor,
        start: occurrenceStart.toISOString(),
        end: occurrenceEnd ? occurrenceEnd.toISOString() : null,
        resourceIds: [],
        entrytype: "event",
        eventId: event.id
      }

      if(event.profiles.length > 0) {
        event.profiles.forEach(profile => {
          returnData.resourceIds.push(`P-${profile}`)
        })
      }

      if(event.vehicles.length > 0) {
        event.vehicles.forEach(vehicle => {
          returnData.resourceIds.push(`F-${vehicle}`)
        })
      }

      if(event.inventoryitems.length > 0) {
        event.inventoryitems.forEach(inventoryitem => {
          returnData.resourceIds.push(`I-${inventoryitem}`)
        })
      }

      if(event.inventoryitemgroups.length > 0) {
        event.inventoryitemgroups.forEach(inventoryitemgroup => {
          returnData.resourceIds.push(`G-${inventoryitemgroup}`)
        })
      }

      return returnData
    })
  })

  sourceAbsenceRequests.value.forEach(absencerequest => {
    timelineEvents.push({
      title: `${absencerequest.reason}`,
      backgroundColor: "red",
      borderColor: "red",
      start: absencerequest.startDate,
      end: absencerequest.endDate,
      resourceIds: [`P-${absencerequest.profile.id}`],
      entrytype: "absencerequest",
      allDay: true,
      absencerequestId: absencerequest.id
    })
  })

  calendarOptionsTimeline.value.initialEvents = timelineEvents
}
const calendarOptionsGrid = computed(() => {
  return {
    locale: deLocale,
    plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin],
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay'
    },
    initialView: "timeGridWeek",
    initialEvents: events.value,
    nowIndicator: true,
    height: "80vh",
    selectable: true,
    weekNumbers: true,
    select: function (info) {
      console.log(info)

      router.push(`/standardEntity/events/create/?startDate=${encodeURIComponent(info.startStr)}&endDate=${encodeURIComponent(info.endStr)}`)
    },
    eventClick: function (info) {
      console.log(info.event)
      if(info.event.extendedProps.entrytype === "absencerequest"){
        router.push(`/standardEntity/absencerequests/show/${info.event.extendedProps.absencerequestId}`)
      } else {
        router.push(`/standardEntity/events/show/${info.event.extendedProps.eventId}`)
      }

    },
    datesSet: function(info) {
      expandEventsForRange(info.startStr, info.endStr)
    }
  }
})

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

  headerToolbar: {
    left: 'prev,next',
    center: 'title',
    right: 'resourceTimelineDay,resourceTimeline3Hours,resourceTimelineMonth'
  },
  initialEvents: [{
    title:"Test",
    resourceId:"F-27",
    start:"2025-01-01"
  }],
  selectable: true,
  select: function (info) {
    router.push(`/standardEntity/events/create?startDate=${encodeURIComponent(info.startStr)}&endDate=${encodeURIComponent(info.endStr)}&resources=${encodeURIComponent(JSON.stringify([info.resource.id]))}&source=timeline`)
  },
  eventClick: function (info){
    console.log(info.event)
    if(info.event.extendedProps.entrytype === "absencerequest"){
      router.push(`/standardEntity/absencerequests/show/${info.event.extendedProps.absencerequestId}`)
    } else {
      router.push(`/standardEntity/events/show/${info.event.extendedProps.eventId}`)
    }
  },
  datesSet: function(info) {
    expandEventsForRange(info.startStr, info.endStr)
  },
  resourceGroupField: "type",
  resourceOrder: "-type",
  resources: [],
  nowIndicator:true,
  views: {
    resourceTimeline3Hours: {
      type: 'resourceTimeline',
      duration: {weeks: 1},
      weekends: false,
      slotDuration: {hours: 3},
      slotMinTime: "06:00:00",
      slotMaxTime: "21:00:00",
      buttonText: "Woche",
      visibleRange: function(currentDate) {
        // Generate a new date for manipulating in the next step
        var startDate = new Date(currentDate.valueOf());
        var endDate = new Date(currentDate.valueOf());

        // Adjust the start & end dates, respectively

        console.log(startDate.getDay())

        startDate.setDate(startDate.getDate() - 1); // One day in the past
        endDate.setDate(endDate.getDate() + 2); // Two days into the future

        return { start: startDate, end: endDate };
      }
    }
  },
  height: '80vh',
})

const loaded = ref(false)
const setupPage = async () => {
  sourceEvents.value = (await useEntities("events").select()).filter(i => !i.archived)
  sourceAbsenceRequests.value = (await useEntities("absencerequests").select("*, profile(*)")).filter(i => !i.archived)
  sourceProjects.value = (await useEntities("projects").select( "*")).filter(i => !i.archived)
  sourceInventoryItems.value = (await useEntities("inventoryitems").select()).filter(i => !i.archived)
  sourceInventoryItemGroups.value = (await useEntities("inventoryitemgroups").select()).filter(i => !i.archived)
  sourceProfiles.value = (await useEntities("profiles").select()).filter(i => !i.archived)
  sourceVehicles.value = (await useEntities("vehicles").select()).filter(i => !i.archived)

  calendarOptionsTimeline.value.resources = [
    ...sourceProfiles.value.filter(i => i.tenant === profileStore.currentTenant).map(profile => {
      return {
        type: 'Mitarbeiter',
        title: profile.fullName,
        id: `P-${profile.id}`
      }
    }),
    ...sourceVehicles.value.map(vehicle => {
      return {
        type: 'Fahrzeug',
        title: vehicle.licensePlate,
        id: `F-${vehicle.id}`
      }
    }),
    ...sourceInventoryItems.value.filter(i=> i.usePlanning).map(item => {
      return {
        type: 'Inventar',
        title: item.name,
        id: `I-${item.id}`
      }
    }),
    ...sourceInventoryItemGroups.value.filter(i=> i.usePlanning).map(item => {
      return {
        type: 'Inventargruppen',
        title: item.name,
        id: `G-${item.id}`
      }
    })
  ]

/*
  calendarOptionsTimeline.value.initialEvents = [
      ...events.value.map(event => {
        let eventColor = profileStore.ownTenant.calendarConfig.eventTypes.find(type => type.label === event.eventtype).color

        let title = ""
        if (event.name) {
          title = event.name
        } else if (event.project) {
          projects.find(i => i.id === event.project) ? projects.find(i => i.id === event.project).name : ""
        }

        let resource = ""
        let resourceType = ""



        return {
          ...event,
          start: event.startDate,
          end: event.endDate,
          title: title,
          borderColor: eventColor,
          textColor: eventColor,
          backgroundColor: "black"
        }
      })
  ]
*/

  expandEventsForRange(dayjs().startOf("month").toISOString(), dayjs().endOf("month").toISOString())

  loaded.value = true

}

setupPage()


//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"}
      }
    }


  })
}
*/




//Calendar Config



</script>

<template>
    <UDashboardNavbar title="Kalender">
      <template #center>
        <h1
            :class="['text-xl','font-medium']"
        >Kalender</h1>
      </template>
      <template #right>

      </template>
    </UDashboardNavbar>
  <UDashboardPanelContent>
    <div v-if="mode === 'grid' && loaded" class="p-5">
      <FullCalendar
          :options="calendarOptionsGrid"
      />
    </div>
    <div v-else-if="mode === 'timeline' && loaded"  class="p-5">
    <FullCalendar
        :options="calendarOptionsTimeline"
    />
  </div>
  </UDashboardPanelContent>



</template>

<style scoped>

</style>
