import * as React from "react";
import { ErrorBoundary as ReactErrorBoundary } from "react-error-boundary";
import { omitCommonProps } from "../../utils/props";
import * as styles from "./styles.module.css";

function Fallback({ error, resetErrorBoundary }) {
  return (
    <div role="alert" className={styles.error}>
      <p className={styles.title}>Something went wrong.</p>
      <details className={styles.message}>{error.message}</details>
      <button className={styles.button} onClick={resetErrorBoundary}>
        Reset
      </button>
    </div>
  );
}

export function ErrorBoundary({ children, className, ...props }) {
  return (
    <ReactErrorBoundary
      FallbackComponent={Fallback}
      onError={(error, info) => {
        // Error occurred in your component hierarchy
        console.error(error, info);
      }}
      onReset={(details) => {
        console.log(details);
        window.location.reload();
        // Reset the state of your app so the error doesn't happen again
      }}
    >
      {React.Children.map(children, (child) =>
        React.cloneElement(child as any, omitCommonProps(props)),
      )}
    </ReactErrorBoundary>
  );
}
