import React, { ReactNode, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { TableState } from '../../state';
import { CollectionTableContentCard } from './CollectionTableContentCard';
import { TableFloatingScrollBar } from '@wix/design-system';

export interface CollectionTableContentBaseProps {
  children?: ReactNode;
}

export interface CollectionTableContentProps<T, F extends FiltersMap>
  extends CollectionTableContentBaseProps {
  state: TableState<T, F>;
}

function _CollectionTableContent<T, F extends FiltersMap = FiltersMap>(
  props: CollectionTableContentProps<T, F>,
) {
  const { state: tableState, children } = props;

  const state = tableState.toolbar;

  const {
    showInitialLoader,
    showEmptyState,
    multi: { showRefreshLoader, showErrorState },
    internalScroll,
  } = state;

  const floatingScrollBarEnabled = state.container.internalExperiments?.enabled(
    'specs.cairo.HorizontalScrollWithScrollBarNewUX',
  );

  const showTableContent =
    !showInitialLoader &&
    !showRefreshLoader &&
    !showErrorState &&
    (!internalScroll || !showEmptyState);

  const [onFullRenderEnd] = useState(() =>
    state.fedopsReporter.onFullRenderStart(),
  );

  useEffect(() => {
    if (showTableContent) {
      onFullRenderEnd();
    }
  }, [showTableContent]);

  if (!showTableContent) {
    return null;
  }

  return (
    <>
      {floatingScrollBarEnabled && <TableFloatingScrollBar zIndex={1} />}
      <CollectionTableContentCard>{children}</CollectionTableContentCard>
    </>
  );
}

export const CollectionTableContent = observer(_CollectionTableContent);
