'use client'

import { forwardRef } from 'react'
import { PktInputWrapper } from '../inputwrapper/InputWrapper'
import { DatepickerPopup } from './DatepickerPopup'
import { DatepickerInputs } from './DatepickerInputs'
import { useDatepickerState } from './useDatepickerState'
import type { IPktDatepicker } from './types'

export type { IPktDatepicker } from './types'

export const PktDatepicker = forwardRef<HTMLDivElement, IPktDatepicker>((props, ref) => {
  const state = useDatepickerState(props, ref)

  const outerClasses = ['pkt-datepicker', state.className].filter(Boolean).join(' ')

  return (
    <div className={outerClasses} id={state.id || undefined}>
      <PktInputWrapper
        ref={state.wrapperRef}
        forId={state.inputId}
        label={state.label}
        hasFieldset={state.hasFieldset}
        inline={state.inline}
        helptext={state.helptext}
        helptextDropdown={state.helptextDropdown}
        helptextDropdownButton={state.helptextDropdownButton}
        hasError={state.hasError}
        errorMessage={state.errorMessage}
        disabled={state.disabled}
        optionalTag={state.optionalTag}
        optionalText={state.optionalText}
        requiredTag={state.requiredTag}
        requiredText={state.requiredText}
        tagText={state.tagText}
        useWrapper={state.useWrapper}
        counter={state.hasCounter}
        counterCurrent={state.values.length}
        counterMaxLength={state.maxlength}
      >
        <DatepickerInputs state={state} />
      </PktInputWrapper>

      <DatepickerPopup
        open={state.calendarOpen}
        multiple={state.multiple}
        range={state.range}
        weeknumbers={state.weeknumbers}
        withcontrols={state.withcontrols}
        selected={state.values}
        earliest={state.minStr}
        latest={state.maxStr}
        excludedates={state.excludedates}
        excludeweekdays={state.excludeweekdays}
        maxMultiple={state.maxlength}
        currentmonth={state.effectiveCurrentMonth}
        today={state.today}
        inputRef={state.inputRef}
        hasCounter={state.hasCounter}
        onDateSelected={state.handleDateSelected}
        onClose={state.handleCalendarClose}
      />

      {/* Uncontrolled hidden input for onChange event dispatching and form submission */}
      <input
        ref={state.changeInputRef}
        type="text"
        name={state.name}
        onChange={state.onChange}
        tabIndex={-1}
        aria-hidden="true"
        className="pkt-visually-hidden"
      />
    </div>
  )
})

PktDatepicker.displayName = 'PktDatepicker'
