import {
  TextArea as RTextArea,
  type TextAreaProps as RTextAreaProps,
} from '@radix-ui/themes';
import { forwardRef, useMemo } from 'react';

type TextAreaProps = RTextAreaProps & {
  error?: boolean;
};

const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
  (props, ref) => {
    const { error, style, className, ...rest } = props;
    const fieldStyle = useMemo(() => {
      if (!error) return style;
      const errorStyle = {
        boxShadow: 'inset 0 0 0 var(--text-area-border-width) var(--error-11)',
      };

      return { ...(style || {}), ...errorStyle };
    }, [error, style]);

    const classNameStr = error ? `error ${className}` : className;

    return (
      <RTextArea
        {...rest}
        className={classNameStr}
        ref={ref}
        style={fieldStyle}
      />
    );
  }
);

TextArea.displayName = 'TextArea';

export { TextArea, type TextAreaProps };
