import React, { forwardRef, useEffect, useRef } from 'react';
import classNames from 'clsx';
import type { BoxProps } from '@mui/material';
import { Box as MuiBox } from '@mui/material';

import { omitUndefinedProps } from '@/mui/helpers';

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

type Props = {
  fullWidth?: boolean;
  inverseScroll?: boolean;
  inverseYScroll?: boolean;
};

const TableScroll = forwardRef<HTMLSpanElement, BoxProps & Props>((props, ref) => {
  const innerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (props.inverseYScroll) {
      if (innerRef.current) {
        innerRef.current?.scrollTo(innerRef.current.clientWidth, 0);
      }
    }
  }, [props.inverseYScroll, innerRef.current]);

  return (
    <MuiBox
      {...omitUndefinedProps({
        ...props,
        inverseScroll: undefined,
        inverseYScroll: undefined,
        fullWidth: undefined,
      })}
      ref={(node) => {
        if (typeof ref === 'function') {
          ref(node as HTMLElement);
        } else if (ref) {
          ref.current = node as HTMLElement;
        }

        innerRef.current = node as HTMLDivElement;
      }}
      className={classNames(props.className, styles.TableScroll, {
        [styles.TableScroll___fullWidth]: props.fullWidth ?? true,
        [styles.TableScroll___windowsNavigator]:
          typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent) && props.inverseScroll,
        [styles.TableScroll___inverseScroll]: props.inverseScroll,
        [styles.TableScroll___inverseYScroll]: props.inverseYScroll,
      })}
    />
  );
});

TableScroll.displayName = 'TableScroll';

export default TableScroll;
