import { TextField as RTextField } from '@radix-ui/themes';
import { forwardRef, useMemo } from 'react';

type RSlotProps = RTextField.SlotProps;

type RootProps = RTextField.RootProps & { error?: boolean };

const Root = forwardRef<
  HTMLInputElement,
  RTextField.RootProps & { error?: boolean }
>((props, ref) => {
  const { error, style, className, ...rest } = props;

  const fieldStyle = useMemo(() => {
    if (!error) return style;
    const errorStyle = {
      boxShadow: 'inset 0 0 0 var(--text-field-border-width) var(--error-11)',
    };

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

  const classNameStr = error ? `error ${className}` : className;
  return (
    <RTextField.Root
      className={classNameStr}
      ref={ref}
      style={fieldStyle}
      {...rest}
    />
  );
});

Root.displayName = 'TextField.Root';

const TextField = { Root, Slot: RTextField.Slot };

export { TextField };
export type { RootProps, RSlotProps as SlotProps };
