'use client'

import { type ForwardedRef, forwardRef, useImperativeHandle } from 'react'
import { useCalendarState } from './useCalendarState'
import { CalendarNav } from './CalendarNav'
import { CalendarGrid } from './CalendarGrid'
import type { IPktCalendar, PktCalendarHandle } from './types'

export type { IPktCalendar, IPktCalendarStrings, PktCalendarHandle } from './types'

export const PktCalendar = forwardRef<PktCalendarHandle, IPktCalendar>((
  props,
  ref: ForwardedRef<PktCalendarHandle>,
) => {
  const state = useCalendarState(props)

  useImperativeHandle(ref, () => ({
    handleDateSelect: state.handleDateSelect,
    addToSelected: state.addToSelected,
    removeFromSelected: state.removeFromSelected,
    toggleSelected: state.toggleSelectedDate,
    focusOnCurrentDate: state.focusOnCurrentDate,
    close: state.close,
  }), [state.handleDateSelect, state.addToSelected, state.removeFromSelected, state.toggleSelectedDate, state.focusOnCurrentDate, state.close])

  return (
    <div
      ref={state.calendarRef}
      className={[
        'pkt-calendar',
        state.weeknumbers && 'pkt-cal-weeknumbers',
        state.className,
      ].filter(Boolean).join(' ')}
      onBlur={state.handleFocusOut}
      onKeyDown={state.handleKeydown}
    >
      <CalendarNav
        componentId={state.componentId}
        strings={state.strings}
        year={state.year}
        month={state.month}
        earliest={state.earliest}
        latest={state.latest}
        withcontrols={state.withcontrols}
        prevMonth={state.prevMonth}
        nextMonth={state.nextMonth}
        changeMonth={state.changeMonth}
      />
      <CalendarGrid state={state} />
    </div>
  )
})

PktCalendar.displayName = 'PktCalendar'
