<script setup lang="ts">
import type { CalendarOptions } from '@fullcalendar/core'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import FullCalendar from '@fullcalendar/vue3'
import { useRtl } from 'vuetify'
import { INITIAL_EVENTS, createEventId } from './event-utils'

interface Event {
  id: string
  startStr: string
  title: string
  start: string
  end: string
  allDay: boolean
}

const currentEvents = ref<Event[]>([])

const { isRtl } = useRtl()

const handleDateSelect = (selectInfo: any) => {
  // eslint-disable-next-line no-alert
  const title = prompt('Please enter a new title for your event')
  const calendarApi = selectInfo.view.calendar

  calendarApi.unselect() // clear date selection

  if (title) {
    calendarApi.addEvent({
      id: createEventId(),
      title,
      start: selectInfo.startStr,
      end: selectInfo.endStr,
      allDay: selectInfo.allDay,
    })
  }
}

const handleEventClick = (clickInfo: any) => {
  // eslint-disable-next-line no-alert
  if (confirm(`Are you sure you want to delete the event '${clickInfo.event.title}'`))
    clickInfo.event.remove()
}

const handleEvents = (events: any) => {
  currentEvents.value = events
}

const calendarOptions = computed(() => {
  return {
    plugins: [
      dayGridPlugin,
      timeGridPlugin,
      interactionPlugin, // needed for dateClick
    ],
    headerToolbar: {
      start: 'prev,next today',
      center: 'title',
      end: 'dayGridMonth,timeGridWeek,timeGridDay',
    },
    initialView: 'dayGridMonth',
    initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
    editable: true,
    selectable: true,
    selectMirror: true,
    dayMaxEvents: true,
    weekends: true,
    direction: isRtl.value ? 'rtl' : 'ltr',
    select: handleDateSelect,
    eventClick: handleEventClick,
    eventsSet: handleEvents,
    eventClassNames() {
      return [
        // Background Color
        'bg-light-primary text-primary text-xs rounded-sm',
      ]
    },

  /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
  } as CalendarOptions
})

// breadcrumbs
const breadcrumbs = [
  {
    title: 'Home',
    disabled: false,
    to: { path: '/' },
  },
  {
    title: 'Apps',
    disabled: true,
  },
  {
    title: 'Calendar',
    disabled: true,
  },
]
</script>

<template>
  <VRow>
    <!-- Breadcrumbs -->
    <VCol cols="12">
      <VBreadcrumbs
        :items="breadcrumbs"
        divider="-"
        class="px-0"
      />
    </VCol>

    <VCol cols="12">
      <VCard>
        <FullCalendar :options="calendarOptions" />
      </VCard>
    </VCol>
  </VRow>
</template>

<style lang="scss">
@import "@/styles/libs/calendar";
</style>
