import { useEffect } from 'react';
import type { GridScrollParams } from '@mui/x-data-grid-pro';
import { throttleEvent } from '../../../utils';
import type { DataGridProps } from '../types';

export const useStickyColumnHeader = (
  apiRef: DataGridProps['apiRef'],
  toggleStickyHeader: (isSticky: boolean) => void,
  dataGridProps: Pick<DataGridProps, 'autoHeight' | 'disableStickyHeader'>
) => {
  useEffect(() => {
    if (dataGridProps.disableStickyHeader) return;

    const handleWindowScroll = throttleEvent(handleWindowScrollChange);
    if (dataGridProps.autoHeight) {
      window.addEventListener('scroll', handleWindowScroll, true);
    } else {
      apiRef?.current?.subscribeEvent('rowsScroll', handleRowsScroll);
    }

    function handleRowsScroll(gridScrollParams: GridScrollParams) {
      const { top } = gridScrollParams;
      toggleStickyHeader(top > 0);
    }

    function handleWindowScrollChange() {
      const rootEl = apiRef?.current?.rootElementRef?.current;
      const rootRect = rootEl?.getBoundingClientRect();
      const top = rootRect?.top || 0;
      toggleStickyHeader(top < 0);
    }

    return () => {
      if (dataGridProps.autoHeight) {
        window.removeEventListener('scroll', handleWindowScroll, true);
      }
    };
  }, [apiRef, dataGridProps.autoHeight, dataGridProps.disableStickyHeader, toggleStickyHeader]);
};
