import { useEffect, useState } from "react";
import type { FallbackProps } from "react-error-boundary";
import { ErrorBoundary } from "react-error-boundary";
import { useLocation } from "react-router-dom";

function ErrorFallback({ error, resetErrorBoundary, onError }: FallbackProps & { onError?: (error: Error) => void }) {
  const location = useLocation();

  const [initialLocation] = useState(location.pathname);

  useEffect(() => {
    if (onError) {
      onError(error);
      resetErrorBoundary();
      return;
    }
    // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
    if (location.pathname !== initialLocation || !error) {
      resetErrorBoundary();
    } else {
      // eslint-disable-next-line no-console
      console.error("Error occurred", error);
    }
  }, [error, location.pathname, initialLocation, resetErrorBoundary, onError]);

  return (
    <div className="h-full w-full p-l">
      <h1>Something went wrong!</h1>
      <p>Please try again later.</p>
    </div>
  );
}

export default function ComponentErrorBoundary({
  children,
  onError,
}: React.PropsWithChildren<{
  onError?: (error: Error) => void;
}>) {
  return (
    <ErrorBoundary FallbackComponent={(props) => <ErrorFallback {...props} onError={onError} />}>
      {children}
    </ErrorBoundary>
  );
}
