"use client"
import * as LabelPrimitive from "@radix-ui/react-label"
import React, { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
import { classNames } from "../../utils"
import { Text, TextBodyProps } from "../Text"
import { VisuallyHidden } from "../VisuallyHidden"

export type LabelProps = ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
  TextBodyProps & {
    /**
     * Renders an asterisk after the label to indicate that the field is required.
     */
    required?: boolean

    /**
     * Renders the label visually hidden but still accessible to screen readers.
     */
    visuallyHidden?: boolean
  }

/**
 * Renders an accessible label associated with controls.
 */
export const Label = forwardRef<
  ElementRef<typeof LabelPrimitive.Root>,
  LabelProps
>(function Label(
  {
    className,
    size = "md",
    weight = "semibold",
    required,
    visuallyHidden,
    ...props
  },
  ref,
) {
  const content = (
    <Text.Body asChild size={size} weight={weight}>
      <LabelPrimitive.Root
        className={classNames(required && "after:content-['_*']", className)}
        ref={ref}
        {...props}
      />
    </Text.Body>
  )

  if (visuallyHidden) {
    return <VisuallyHidden>{content}</VisuallyHidden>
  }

  return content
})
