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 { GroupBy, RenderSection } from '../CollectionSectionHeader';

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

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

  const { toolbar } = grid;

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

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

  const { sections } = state;

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

  let child;

  if (!sections.length || showInitialLoader || showRefreshLoader) {
    child = (
      <GridSectionsSingleSkeletonGrid {...props} state={state.parentState} />
    );
  } else {
    child = (
      <>
        {sections.map((sectionDescriptor) => (
          <GridSectionAndRepeater
            {...props}
            key={sectionDescriptor.sectionId}
            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);
