'use client'

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

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

export type { IPktSelectOption, TSelectOption } from 'shared-types/select'

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
  inputSize?: 'small' | 'medium' | 'xsmall'
  /** @deprecated Var aldri implementert — bruk children med `<option>`-elementer. */
  options?: never
}

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,
      inputSize = 'medium',
      ...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}
        size={inputSize}
      >
        <select
          ref={ref}
          className={`pkt-input pkt-input--${inputSize} ${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>
    )
  },
)

PktSelect.displayName = 'PktSelect'
