'use client'

import { useEffect, useRef } from 'react'
import { handleCalendarPosition } from 'shared-utils/datepicker-utils'

import { PktCalendar } from '../calendar/Calendar'

interface DatepickerPopupProps {
  open: boolean
  multiple?: boolean
  range?: boolean
  weeknumbers?: boolean
  withcontrols?: boolean
  selected?: string[]
  earliest?: string | null
  latest?: string | null
  excludedates?: string[]
  excludeweekdays?: string[]
  maxMultiple?: number
  currentmonth?: string | null
  today?: string
  inputRef?: React.RefObject<HTMLInputElement | null>
  hasCounter?: boolean
  onDateSelected: (selected: string[]) => void
  onClose: () => void
}

export const DatepickerPopup = ({
  open,
  multiple = false,
  range = false,
  weeknumbers = false,
  withcontrols = false,
  selected = [],
  earliest,
  latest,
  excludedates,
  excludeweekdays,
  maxMultiple,
  currentmonth,
  today,
  inputRef,
  hasCounter = false,
  onDateSelected,
  onClose,
}: DatepickerPopupProps) => {
  const popupRef = useRef<HTMLDivElement>(null)
  const hasBeenOpenedRef = useRef(false)

  if (open) {
    hasBeenOpenedRef.current = true
  }

  useEffect(() => {
    if (open) {
      handleCalendarPosition(popupRef.current, inputRef?.current ?? null, hasCounter)
    }
  }, [open, inputRef, hasCounter])

  const popupClasses = ['pkt-calendar-popup', open ? 'show' : 'hide'].join(' ')
  const shouldRenderCalendar = open || hasBeenOpenedRef.current

  return (
    <div
      ref={popupRef}
      className={popupClasses}
      hidden={!open}
      aria-hidden={!open}
    >
      {shouldRenderCalendar && (
        <PktCalendar
          multiple={multiple}
          range={range}
          weeknumbers={weeknumbers}
          withcontrols={withcontrols}
          selected={selected}
          earliest={earliest}
          latest={latest}
          excludedates={excludedates}
          excludeweekdays={excludeweekdays}
          maxMultiple={maxMultiple}
          currentmonth={currentmonth}
          today={today}
          onDateSelected={onDateSelected}
          onClose={onClose}
        />
      )}
    </div>
  )
}
