'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 './types'

// Each event type maps to a CSS class that drives the dot/bar colour
// (same pattern as BigWig's MiniCalendarGrid — event-bg-primary etc.)
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 matterToDeadlineEvent(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
  view?: 'dayGridMonth' | 'listWeek'
}

const LegalCalendarGrid = ({ hearings, matters, onEventClick, view = 'listWeek' }: Props) => {
  const events = [
    ...hearings.map(hearingToEvent),
    ...matters.map(matterToDeadlineEvent).filter(Boolean),
  ]

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

  return (
    // AppFullCalendar is BigWig's styled FullCalendar wrapper — reuse directly
    // (import path will be @/libs/styles/AppFullCalendar in the actual project)
    <div
      className='legal-calendar'
      style={{
        // Mirror BigWig's AppFullCalendar sizing overrides inline for now
        // until the styled wrapper is ported
      }}
    >
      <FullCalendar
        plugins={[dayGridPlugin, interactionPlugin]}
        initialView='dayGridMonth'
        key='calendar'
        headerToolbar={{ left: 'prev', center: 'title', right: 'next' }}
        events={events as any}
        height='auto'
        fixedWeekCount={false}
        dayMaxEvents={2}
        editable={false}
        selectable={false}
        eventClick={handleEventClick}
      />
    </div>
  )
}

export default LegalCalendarGrid
