"use client"

import type { ITextFieldProps } from "./TextField.d"
import type { JSX } from "react"

import { forwardRef } from "react"

import { TextField as RadixTextField, Text } from "@radix-ui/themes"

export const TextField = forwardRef<HTMLInputElement, ITextFieldProps>(
	(
		{
			id,
			label,
			undertitle,
			error,
			size = "2",
			variant,
			radius,
			startIcon,
			endIcon,
			className,
			style,
			color,
			...rootProps
		},
		ref,
	): JSX.Element => (
		<label htmlFor={id}>
			{label && (
				<Text as="div" size="2" mb="1" weight="medium">
					{label}
				</Text>
			)}
			<RadixTextField.Root
				size={size}
				variant={variant}
				radius={radius}
				color={error ? "red" : color}
				className={className}
				style={style}
				ref={ref}
				aria-describedby={undertitle ? `${id}-undertitle` : undefined}
				aria-invalid={error}
				id={id}
				{...rootProps}
			>
				{startIcon && (
					<RadixTextField.Slot side="left">{startIcon}</RadixTextField.Slot>
				)}
				{endIcon && (
					<RadixTextField.Slot side="right">{endIcon}</RadixTextField.Slot>
				)}
			</RadixTextField.Root>
			{undertitle && (
				<Text as="p" size="1" color="gray" mt="1" id={`${id}-undertitle`}>
					{undertitle}
				</Text>
			)}
		</label>
	),
)

TextField.displayName = "TextField"
