import {
  ChangeEventHandler,
  ForwardedRef,
  forwardRef,
  type InputHTMLAttributes,
  ReactElement,
  ReactNode,
} from 'react'

export interface IPktRadioButton extends InputHTMLAttributes<HTMLInputElement> {
  id: string
  name: string
  label: string
  hasTile?: boolean
  disabled?: boolean
  checkHelptext?: ReactNode | ReactNode[] | string
  defaultChecked?: boolean
  checked?: boolean
  hasError?: boolean
  value?: string
  optionalTag?: boolean
  optionalText?: string
  requiredTag?: boolean
  requiredText?: string
  tagText?: string | null
  onChange?: ChangeEventHandler<HTMLInputElement>
}

export const PktRadioButton = forwardRef(
  (
    {
      id,
      name,
      label,
      className,
      hasTile = false,
      disabled = false,
      checkHelptext,
      hasError = false,
      defaultChecked,
      checked,
      optionalTag,
      optionalText,
      requiredTag,
      requiredText,
      tagText,
      ...props
    }: IPktRadioButton,
    ref: ForwardedRef<HTMLInputElement>,
  ): ReactElement => {
    const classes = [className, 'pkt-input-check'].filter(Boolean).join(' ')

    const inputTileClasses = [
      'pkt-input-check__input',
      hasTile ? 'pkt-input-check__input--tile' : '',
      disabled && hasTile ? 'pkt-input-check__input--tile-disabled' : '',
    ]
      .filter(Boolean)
      .join(' ')

    const inputCheckBoxClasses = [
      'pkt-input-check__input-checkbox',
      hasError ? 'pkt-input-check__input-checkbox--error' : '',
    ]
      .filter(Boolean)
      .join(' ')

    const labelClasses = ['pkt-input-check__input-label', disabled ? 'pkt-input-check__input-label--disabled' : '']
      .filter(Boolean)
      .join(' ')

    const tagClasses = ['pkt-tag', 'pkt-tag--small', 'pkt-tag--thin-text'].join(' ')

    const renderTags = () => {
      return (
        <>
          {tagText && <span className={tagClasses + ` pkt-tag--gray`}>{tagText}</span>}
          {optionalTag && <span className={tagClasses + ` pkt-tag--blue-light`}>{optionalText}</span>}
          {requiredTag && <span className={tagClasses + ` pkt-tag--beige`}>{requiredText}</span>}
        </>
      )
    }

    return (
      <div className={classes}>
        <div className={inputTileClasses}>
          <input
            ref={ref}
            id={id}
            type="radio"
            name={name}
            disabled={disabled}
            className={inputCheckBoxClasses}
            {...(checked !== undefined ? { checked } : { defaultChecked })}
            {...props}
          />
          <label className={labelClasses} htmlFor={id}>
            {label} {renderTags()}
            {checkHelptext && <div className="pkt-input-check__input-helptext">{checkHelptext}</div>}
          </label>
        </div>
      </div>
    )
  },
)

PktRadioButton.displayName = 'PktRadioButton'
