import React, { useState, useEffect, useContext } from 'react';
import { Toast } from '@cloudflare/component-toast';
import FormContext from './FormContext';
import { Trans } from '@cloudflare/intl-react';

let count = 0;

export type Props = {
  errors?: object;
  showErrors?: boolean;
  children?: React.ReactNode;
};

export default function ErrorSummmary({
  errors,
  showErrors = true,
  children
}: Props) {
  const [errorId] = useState(() => `cf-form-error${++count}`);

  const context = useContext(FormContext);
  const errorCount = errors
    ? [...Object.values(errors)].filter(Boolean).length
    : 0;

  const hasErrors = showErrors && errorCount > 0;

  useEffect(() => {
    if (hasErrors) {
      context.setError(context.formName, errorId);
    } else {
      context.removeError(context.formName);
    }
    return () => context.removeError(errorId);
  }, [hasErrors]);

  return hasErrors ? (
    <Toast type="error" id={errorId} role="alert">
      {children ?? (
        <Trans
          id="common.correct_form_errors"
          values={{ smart_count: errorCount }}
        />
      )}
    </Toast>
  ) : (
    <React.Fragment />
  );
}
