import React, { useState } from 'react';
import { GridSectionsState, SectionRange } from './GridSectionsState';
import { FiltersMap } from '@wix/bex-core';
import { Box } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { GridContent, GridContentBaseProps } from '../Grid/GridContent';
import { GridSectionHeader } from './GridSectionHeader';
import { GridSectionsSectionState } from './GridSectionsSectionState';

export interface GridSectionAndRepeaterProps<T, F extends FiltersMap>
  extends GridContentBaseProps<T, F> {
  sectionDescriptor: SectionRange;
  state: GridSectionsState<T, F>;
}

function _GridSectionAndRepeater<T, F extends FiltersMap>(
  props: GridSectionAndRepeaterProps<T, F>,
) {
  const { sectionDescriptor, imagePlacement, layoutType, dragAndDrop } = props;

  const { range } = sectionDescriptor;

  const [state] = useState(
    () =>
      new GridSectionsSectionState({
        gridSections: props.state,
        sectionDescriptor,
        imagePlacement,
        layoutType,
        draggable: dragAndDrop ? 'draggable' : 'none',
      }),
  );

  return (
    <Box direction="vertical" width="100%" dataHook="grid-section-and-repeater">
      <GridSectionHeader sectionDescriptor={sectionDescriptor} state={state} />

      <GridContent
        {...props}
        paddingTop={layoutType === 'list' ? undefined : 'SP4'}
        range={range}
        state={state.gridBase}
        withInfiniteScrollLoader={state.isLast}
      />
    </Box>
  );
}

export const GridSectionAndRepeater = observer(_GridSectionAndRepeater);
