import React, { ReactNode } from 'react';
import { observer } from 'mobx-react-lite';
import { TaskState } from '@wix/bex-core';
import { ErrorState, ErrorStateProps } from '../ErrorState';
import { CollectionEmptyState } from '../EmptyState/CollectionEmptyState';
import { CollectionNoResultsState } from '../EmptyState/CollectionNoResultsState';

export interface PlaceholderStatesBaseProps {
  state: {
    initTask: TaskState<unknown>;
    showLoadingState: boolean;
    showEmptyState: boolean;
    hasAvailableItems: boolean;
    resultOriginQuerySearch?: string;
    hasNonPersistentActiveFilters: boolean;
    showErrorState: boolean;
    errorStatus:
      | {
          error: unknown;
        }
      | null
      | undefined;
    retryErrorState: () => void;
  };
  renderError?: ErrorStateProps['renderError'];
  errorState?: ErrorStateProps['errorState'];
  emptyState?: ReactNode;
  noResultsState?: ReactNode;
  loadingState?: ReactNode;
  children?: ReactNode;
}

function _PlaceholderStatesBase(props: PlaceholderStatesBaseProps) {
  const {
    state,
    emptyState,
    noResultsState: noResultsStateProp,
    errorState,
    children,
    loadingState,
  } = props;

  const {
    initTask,
    showLoadingState,
    showEmptyState,
    hasAvailableItems,
    resultOriginQuerySearch,
    hasNonPersistentActiveFilters,
    showErrorState,
    errorStatus,
  } = state;

  const noResultsState =
    typeof noResultsStateProp === 'function'
      ? noResultsStateProp()
      : noResultsStateProp;

  let child: ReactNode;

  if (initTask.status.isError) {
    child = (
      <ErrorState
        dataHook="placeholder-states-error-state"
        errorStatus={initTask.status}
        state={state}
        errorState={errorState}
      />
    );
  } else if (showLoadingState) {
    child = loadingState || children;
  } else if (showErrorState && errorStatus) {
    child = (
      <ErrorState
        dataHook="placeholder-states-error-state"
        errorStatus={errorStatus}
        state={state}
        errorState={errorState}
      />
    );
  } else if (showEmptyState) {
    if (
      hasAvailableItems &&
      (resultOriginQuerySearch != null || hasNonPersistentActiveFilters)
    ) {
      if (noResultsState) {
        child = noResultsState;
      } else {
        child = <CollectionNoResultsState />;
      }
    } else {
      if (emptyState) {
        child = emptyState;
      } else {
        child = <CollectionEmptyState />;
      }
    }
  } else {
    child = children;
  }

  return <>{child}</>;
}

export const PlaceholderStatesBase = observer(_PlaceholderStatesBase);
