import { cx } from "class-variance-authority"
import { forwardRef, type ForwardedRef, useId } from "react"
import { TextArea as AriaTextArea } from "react-aria-components"

import { InputLabel } from "../InputLabel"
import { Typography } from "../Typography"

import styles from "./textarea.module.css"
import type { TextAreaProps } from "./types"

const TextAreaComponent = forwardRef(function TextAreaComponent(
  { label, placeholder, id, required, ...props }: TextAreaProps,
  ref: ForwardedRef<HTMLTextAreaElement>
) {
  const generatedId = useId()
  const textareaId = id || generatedId

  return (
    <>
      {label && (
        <InputLabel required={required} className={styles.labelAbove}>
          {label}
        </InputLabel>
      )}
      <label className={styles.container} htmlFor={textareaId}>
        <Typography variant="Body/Paragraph/mdRegular">
          <AriaTextArea
            {...props}
            id={textareaId}
            required={required}
            placeholder={placeholder ?? ""}
            className={cx(styles.textarea, props.className)}
            ref={ref}
          />
        </Typography>
      </label>
    </>
  )
})

export const TextArea = TextAreaComponent as React.ForwardRefExoticComponent<
  TextAreaProps & React.RefAttributes<HTMLTextAreaElement>
>
