import React, { ReactElement, ReactNode } from 'react';
import { observer } from 'mobx-react-lite';
import { TaskState } from '@wix/bex-core';

function _InitialLoadingConditional({
  children = null,
  loadingElement = null,
  hideLoadingElement,
  state,
}: {
  children?: ReactNode;
  hideLoadingElement?: boolean;
  loadingElement?: ReactElement | null;
  state: { initTask: TaskState<unknown> };
}) {
  const { initTask } = state;
  const { status } = initTask;
  const { isLoading, isIdle } = status;

  if (initTask.status.isError) {
    return null;
  }

  if (hideLoadingElement) {
    return <>{children}</>;
  }

  if (isIdle || isLoading) {
    return loadingElement;
  }

  return <>{children}</>;
}

export const InitialLoadingConditional = observer(_InitialLoadingConditional);
