import React, { useEffect, useContext } from 'react';
import Error from './Error';
import FormContext from './FormContext';

type Props = {
  name: string;
} & Omit<React.ComponentProps<typeof Error>, 'id'>;

export default function ContextError({ name, children, ...rest }: Props) {
  const context = useContext(FormContext);
  const errorId = `cf-form-error-${name}`;
  const hasChildren = !!children;
  useEffect(() => {
    if (hasChildren) {
      context.setError(name, errorId);
    } else {
      context.removeError(name);
    }
    return () => context.removeError(name);
  }, [hasChildren]);

  return hasChildren ? (
    <Error id={errorId} {...rest}>
      {children}
    </Error>
  ) : (
    <React.Fragment />
  );
}
