import React, { ReactNode, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { CollectionTableContentCard } from '../CollectionTable/CollectionTableContentCard';
import { useWixPatternsRouter } from '../../providers/WixPatternsRouterProvider';

export interface NestedTableContentContentBaseProps {
  children?: ReactNode;
}

export interface NestedTableContentContentProps
  extends NestedTableContentContentBaseProps {
  state: {
    showLoadingState: boolean;
    showErrorState: boolean;
    init: ({ isUsingCache }: { isUsingCache?: boolean }) => () => void;
  };
}

function _NestedTableContent(props: NestedTableContentContentProps) {
  const { state, children } = props;

  const { showLoadingState, showErrorState } = state;

  const showTableContent = !showLoadingState && !showErrorState;
  const router = useWixPatternsRouter();

  useEffect(() => {
    // Pass isUsingCache: true to prevent another fetch
    return state.init({ isUsingCache: router?.isUsingCache });
  }, [router?.isUsingCache]);

  return (
    <>
      {showTableContent && (
        <CollectionTableContentCard>{children}</CollectionTableContentCard>
      )}
    </>
  );
}

export const NestedTableContent = observer(_NestedTableContent);
