'use client'

import { ForwardedRef, forwardRef, ReactNode, SelectHTMLAttributes } from 'react'

import { PktInputWrapper } from '../inputwrapper/InputWrapper'

export type TSelectOption = {
  value: string
  label: string
  selected?: boolean
  disabled?: boolean
}

export interface IPktSelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
  ariaDescribedby?: string
  ariaLabelledby?: string
  children?: ReactNode | ReactNode[]
  disabled?: boolean
  errorMessage?: string | ReactNode | ReactNode[]
  hasError?: boolean
  helptext?: string | ReactNode | ReactNode[]
  helptextDropdown?: string | ReactNode | ReactNode[]
  helptextDropdownButton?: string
  id: string
  inline?: boolean
  fullwidth?: boolean
  label: string
  name?: string
  optionalTag?: boolean
  optionalText?: string
  requiredTag?: boolean
  requiredText?: string
  tagText?: string | null
  options?: Array<{ value: string; label: string; disabled?: boolean }>
}

export const PktSelect = forwardRef(
  (
    {
      ariaDescribedby,
      ariaLabelledby,
      children,
      className,
      disabled = false,
      errorMessage,
      hasError,
      helptext,
      helptextDropdown,
      helptextDropdownButton,
      id,
      inline = false,
      fullwidth = false,
      label,
      name,
      optionalTag = false,
      optionalText,
      requiredTag = false,
      requiredText,
      tagText,
      ...props
    }: IPktSelectProps,
    ref: ForwardedRef<HTMLSelectElement>,
  ) => {
    const classNames = [className, 'pkt-select'].join(' ')
    return (
      <PktInputWrapper
        className={classNames}
        forId={`${id}-input`}
        label={label}
        helptext={helptext}
        helptextDropdown={helptextDropdown}
        helptextDropdownButton={helptextDropdownButton}
        optionalTag={optionalTag}
        optionalText={optionalText}
        requiredTag={requiredTag}
        requiredText={requiredText}
        tagText={tagText}
        hasError={hasError}
        errorMessage={errorMessage}
        disabled={disabled}
        inline={inline}
        ariaDescribedby={ariaDescribedby}
      >
        <select
          ref={ref}
          className={`pkt-input ${fullwidth ? 'pkt-input--fullwidth' : ''}`}
          aria-invalid={hasError}
          aria-errormessage={`${id}-error`}
          aria-labelledby={ariaLabelledby || undefined}
          disabled={disabled}
          id={`${id}-input`}
          name={name || id}
          {...props}
        >
          {children}
        </select>
      </PktInputWrapper>
    )
  },
)
