import React from 'react'

import { cn } from '../../services/cn'
import Icon from '../Icons/Icon'
import Tooltip from '../Tooltip/Tooltip'
import { type TooltipProps } from '../Tooltip/Tooltip'

export type FormLabelProps = {
  /** The string or element that will display for the label. */
  label: React.ReactNode
  /** Optional prop for a secondary label. This will appear to the right of the label. */
  rightLabel?: React.ReactNode
  /** Optional prop for a tooltip. This will appear as a blue info icon to the right of the label. */
  tooltip?: Omit<TooltipProps, 'children'>
  /** Optional prop to show that the field is required. A red asterisk will appear next to the label. */
  required?: boolean
  /** Optional prop to style the label when the corresponding field has an error. */
  error?: boolean
  /** Optional prop to style the label when the corresponding field is disabled. */
  disabled?: boolean
  /** Optional prop to allow an id to be passed in. This will allow the form element to be selected when clicking on the label. */
  id?: string
  /** Optional prop to add a test id to the FormLabel for QA testing */
  qaTestId?: string
}

const labelColorVariants = {
  error: 'text-dark-red',
  disabled: 'text-medium-gray',
  standard: 'text-dark-purple',
} as const

const FormLabel = ({
  label,
  rightLabel,
  tooltip,
  required,
  error,
  id,
  disabled,
  qaTestId = 'form-label',
}: FormLabelProps): React.JSX.Element => {
  // Get the correct color variant
  const colorVariant = error ? 'error' : disabled ? 'disabled' : 'standard'

  return (
    <label
      className={cn(
        'mb-2 flex flex-grow items-center justify-between gap-2 text-xs font-normal',
        labelColorVariants[colorVariant],
      )}
      htmlFor={id}
      data-testid='form-label'
      qa-test-id={qaTestId}
    >
      <div className='flex items-center gap-2'>
        <span>
          {label}
          {required ? <span className='ml-0.5 text-dark-red'>*</span> : null}
        </span>
        {tooltip ? (
          <Tooltip position='right' {...tooltip}>
            <Icon icon='info' color='dark-blue' iconSize='12px' />
          </Tooltip>
        ) : null}
      </div>
      {rightLabel ? <div>{rightLabel}</div> : null}
    </label>
  )
}

export default FormLabel
