'use client'

import { forwardRef } from 'react'
import { PktInputWrapper } from '../inputwrapper/InputWrapper'
import { ComboboxInput } from './ComboboxInput'
import { ComboboxTags } from './ComboboxTags'
import { Listbox } from './Listbox'
import { useComboboxState } from './useComboboxState'
import type { IPktCombobox } from './types'

export type { IPktCombobox } from './types'

export const PktCombobox = forwardRef<HTMLDivElement, IPktCombobox>((props, ref) => {
  const state = useComboboxState(props, ref)

  const outerClasses = [
    'pkt-combobox-component',
    state.fullwidth && 'pkt-combobox-component--fullwidth',
    state.className,
  ]
    .filter(Boolean)
    .join(' ')

  const hasTextInput = state.allowUserInput || state.typeahead
  const wrapperForId = hasTextInput ? state.inputId : `${state.id}-combobox`

  return (
    <div className={outerClasses} ref={state.wrapperRef} id={state.id || undefined}>
      <PktInputWrapper
        forId={wrapperForId}
        hasFieldset={!hasTextInput}
        label={state.label || ''}
        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}
        size={props.inputSize ?? 'medium'}
        counter={state.hasCounter}
        counterCurrent={state.values.length}
        counterMaxLength={state.maxlength}
        className="pkt-combobox__wrapper"
      >
        <div className="pkt-combobox" onBlur={state.handleFocusOut}>
          <ComboboxInput state={state} />
          <Listbox state={state} />
        </div>

        {state.tagPlacement === 'outside' && state.multiple && <ComboboxTags state={state} outside />}
      </PktInputWrapper>

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

PktCombobox.displayName = 'PktCombobox'
