import { FormMessage, useFormField } from "@/ui";
import { t } from "i18next";
import * as React from "react";

export const FormErrorMessage = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLParagraphElement>
>(({ children, ...props }, ref) => {
  const { error } = useFormField();
  let message = children;

  if (error) {
    if (error.message) {
      message = String(error?.message || error.root?.message);
    } else {
      if (error.type === "required") {
        message = t("common.required_field");
      }
    }
  }

  return (
    <FormMessage ref={ref} {...props}>
      {message}
    </FormMessage>
  );
});
FormErrorMessage.displayName = "FormErrorMessage";
