import React, { CSSProperties, forwardRef, useMemo } from 'react';
import classNames from 'clsx';
import type { BoxProps } from '@mui/material';
import { Box as MuiBox } from '@mui/material';
import { useTheme } from '@mui/material/styles';

import { getNumberInRange, isInRange } from '@/modules/@common/helpers/number';

import styles from './DotPagination.module.scss';

const size = 8;

type Props = {
  boundaryCount: number;
  count: number;
  page: number;
};

const DotPagination = forwardRef<HTMLElement, BoxProps & Props>((props, ref) => {
  const theme = useTheme();
  const spacing = theme.spacing(1);
  const boundaryCount = props.boundaryCount ?? 5;
  const activeIndex = Math.max(0, props.page - 1);
  const spacingNum = parseInt(spacing, 10);
  const activeShiftIndex = getNumberInRange(activeIndex - 2, 0, props.count - boundaryCount);

  const items = useMemo(() => new Array(props.count).fill(0).map((_, index) => index), [props.count]);

  return (
    <MuiBox
      ref={ref}
      className={styles.Wrapper}
      style={
        {
          '--internal-boundary-count': boundaryCount,
          '--internal-active-shift-index': activeShiftIndex,
          '--internal-shift-transform': `${activeShiftIndex * -1 * (size + spacingNum)}px`,
        } as CSSProperties
      }
    >
      <div className={styles.Content}>
        {items.map((id) => (
          <div
            key={`item-${id}`}
            className={classNames(styles.Item, {
              [styles.Item___active]: activeIndex === id,
              [styles.Item___primary]:
                activeIndex !== id &&
                isInRange(
                  id,
                  activeIndex - (activeIndex >= props.count - 1 ? 2 : 1),
                  activeIndex + (activeIndex === 0 ? 2 : 1),
                ),
            })}
          />
        ))}
      </div>
    </MuiBox>
  );
});

DotPagination.displayName = 'DotPagination';

export default DotPagination;
