import { GridSectionsState } from './GridSectionsState';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { GridSectionAndRepeater } from './GridSectionAndRepeater';
import React, { useEffect, useState } from 'react';
import { GridContentBaseProps } from '../Grid/GridContent';
import { GridState } from '../../state';
import { runInAction } from 'mobx';
import { Box } from '@wix/design-system';
import { GridSectionsSingleSkeletonGrid } from './GridSectionsSingleSkeletonGrid';
import type { RenderSection } from '../CollectionSectionHeader';

export interface GridSectionsContentProps<T, F extends FiltersMap>
  extends GridContentBaseProps<T, F> {
  state: GridState<T, F>;
  renderSection?: RenderSection<T>;
}

function _GridSectionsContent<T, F extends FiltersMap>(
  props: GridSectionsContentProps<T, F>,
) {
  const { state: grid, renderSection, layoutType } = props;

  const { toolbar } = grid;

  const {
    showInitialLoader,
    multi: { showRefreshLoader },
  } = toolbar;

  const [state] = useState(
    () =>
      (grid._sections ??= new GridSectionsState({
        toolbar: grid.toolbar,
        collection: grid.collection,
        renderSection,
        parentState: grid,
      })),
  );

  const { sections } = state;

  useEffect(() => {
    runInAction(() => {
      if (renderSection) {
        state.renderSection = renderSection;
      }
    });
  }, [renderSection]);

  let child;

  if (!sections.length || showInitialLoader || showRefreshLoader) {
    child = (
      <GridSectionsSingleSkeletonGrid {...props} state={state.parentState} />
    );
  } else {
    child = (
      <>
        {sections.map((sectionDescriptor) => (
          <GridSectionAndRepeater
            {...props}
            key={sectionDescriptor.section.id}
            sectionDescriptor={sectionDescriptor}
            state={state}
          />
        ))}
      </>
    );
  }

  return (
    <Box
      direction="vertical"
      width="100%"
      paddingTop={layoutType === 'list' ? 'SP2' : undefined}
      paddingBottom={layoutType === 'list' ? 'SP2' : undefined}
    >
      {child}
    </Box>
  );
}

export const GridSectionsContent = observer(_GridSectionsContent);
