import { FC, ReactNode, Suspense, useEffect, memo } from 'react';

import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

// Wrapper component that tracks loading state - defined outside to ensure stable identity
const ChildrenWrapper: FC<{
  children: ReactNode;
  onLoadingChange: (isLoading: boolean) => void;
}> = ({ children, onLoadingChange }) => {
  useEffect(() => {
    onLoadingChange(false);
  }, [onLoadingChange]);
  return <>{children}</>;
};

// Suspense wrapper that tracks loading state
const SuspenseWithLoadingStateComponent: FC<{
  children: ReactNode;
  onLoadingChange: (isLoading: boolean) => void;
  fallback?: ReactNode;
}> = ({ children, onLoadingChange, fallback }) => {
  return (
    <Suspense fallback={fallback || <HuSpinner />}>
      <ChildrenWrapper onLoadingChange={onLoadingChange}>
        {children}
      </ChildrenWrapper>
    </Suspense>
  );
};

export const SuspenseWithLoadingState = memo(SuspenseWithLoadingStateComponent);

SuspenseWithLoadingStateComponent.displayName = 'SuspenseWithLoadingState';
