import { useRef, useState, useCallback } from 'react'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import useProjectStore from '../../store/useProjectStore'
import useFocusStore from '../../store/useFocusStore'
import { updateDeliverable } from '../../api/deliverables'
import DeliverableModal from '../Deliverables/DeliverableModal'

export default function MainCalendar() {
  const calRef = useRef(null)
  const { projects, updateDeliverable: storeUpdate } = useProjectStore()
  const openFocus = useFocusStore(s => s.openFocus)
  const [modal, setModal] = useState({ open: false, deliverable: null, defaultDate: '' })

  const events = projects.flatMap(p =>
    (p.deliverables || []).map(d => ({
      id:              String(d.id),
      title:           `${p.name}: ${d.title}`,
      start:           d.due_date,
      allDay:          true,
      backgroundColor: p.color,
      borderColor:     p.color,
      extendedProps:   { deliverableId: d.id, projectId: p.id },
    }))
  )

  const handleEventDrop  = useCallback(async ({ event }) => {
    const { deliverableId } = event.extendedProps
    storeUpdate(await updateDeliverable(deliverableId, { due_date: event.startStr.substring(0,10) }))
  }, [storeUpdate])

  const handleEventClick = useCallback(({ event }) => {
    const { deliverableId, projectId } = event.extendedProps
    openFocus(projectId, deliverableId)
  }, [openFocus])

  const handleDateClick  = useCallback(({ dateStr }) => {
    setModal({ open: true, deliverable: null, defaultDate: dateStr.substring(0,10) })
  }, [])

  return (
    <div className="h-full flex flex-col bg-surface p-4">
      <div className="flex-1 overflow-hidden">
        <FullCalendar
          ref={calRef}
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          initialView="dayGridMonth"
          headerToolbar={{ left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }}
          events={events}
          editable={true}
          eventDrop={handleEventDrop}
          eventClick={handleEventClick}
          dateClick={handleDateClick}
          height="100%"
          dayMaxEvents={4}
          eventDisplay="block"
          displayEventTime={false}
        />
      </div>
      <DeliverableModal
        isOpen={modal.open}
        onClose={() => setModal({ open: false, deliverable: null, defaultDate: '' })}
        deliverable={modal.deliverable}
        defaultDate={modal.defaultDate}
      />
    </div>
  )
}
