'use client'

import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import type { EventClickArg } from '@fullcalendar/core'
import type { Hearing, Matter } from '@/views/dashboard/types'

function hearingToEvent(h: Hearing) {
  return {
    id: `hearing-${h.id}`,
    title: `${h.time} ${h.matter}`,
    start: `${h.date}T${h.time}`,
    classNames: ['event-bg-primary'],
    extendedProps: { type: 'hearing', refId: h.id },
  }
}

function matterToEvent(m: Matter) {
  if (m.nextActionType !== 'deadline' && m.nextActionType !== 'filing') return null
  return {
    id: `matter-${m.id}`,
    title: m.nextActionType === 'filing' ? `Filing: ${m.reference}` : `Deadline: ${m.reference}`,
    start: m.nextActionDate,
    allDay: true,
    classNames: [m.nextActionType === 'filing' ? 'event-bg-info' : 'event-bg-error'],
    extendedProps: { type: m.nextActionType, refId: m.id },
  }
}

interface Props {
  hearings: Hearing[]
  matters: Matter[]
  onEventClick?: (id: string, type: string) => void
}

export default function FullCalendarView({ hearings, matters, onEventClick }: Props) {
  const events = [
    ...hearings.map(hearingToEvent),
    ...matters.map(matterToEvent).filter(Boolean),
  ]

  const handleEventClick = (info: EventClickArg) => {
    const { type, refId } = info.event.extendedProps
    onEventClick?.(refId, type)
  }

  return (
    <div className='legal-calendar'>
      <FullCalendar
        plugins={[dayGridPlugin, interactionPlugin]}
        initialView='dayGridMonth'
        headerToolbar={{ left: 'prev,next today', center: 'title', right: 'dayGridMonth,dayGridWeek' }}
        events={events as any}
        height='auto'
        fixedWeekCount={false}
        dayMaxEvents={4}
        editable={false}
        selectable={false}
        eventClick={handleEventClick}
      />
    </div>
  )
}
