import { observer } from 'mobx-react-lite';
import { GridBaseState } from '../../state';
import { Box } from '@wix/design-system';
import { FiltersMap } from '@wix/bex-core';
import React, { useMemo } from 'react';
import { SkeletonCardByImagePlacement } from './SkeletonCardByImagePlacement';

export interface SkeletonGridProps<T, F extends FiltersMap> {
  state: GridBaseState<T, F>;
  skeletonRows?: number;
}

function _SkeletonGrid<T, F extends FiltersMap>(
  props: SkeletonGridProps<T, F>,
) {
  const { state, skeletonRows = 2 } = props;

  const {
    calcGridProps: { columnCount },
    itemsContentWidth,
    gap,
  } = state;

  const { gridTemplateColumns, children } = useMemo(() => {
    return {
      gridTemplateColumns: `repeat(${columnCount}, 1fr)`,
      children: new Array(columnCount * skeletonRows)
        .fill(undefined)
        .map((_, i) => <SkeletonCardByImagePlacement state={state} key={i} />),
    };
  }, [columnCount, skeletonRows]);

  if (!itemsContentWidth) {
    return null;
  }

  return (
    <Box
      dataHook="skeleton-grid"
      width="100%"
      display="grid"
      gap={`${gap}px`}
      gridAutoRows="1fr"
      gridTemplateColumns={gridTemplateColumns}
    >
      {children}
    </Box>
  );
}

export const SkeletonGrid = observer(_SkeletonGrid);
