import * as React from 'react';
import type { DataGridProps } from '../types';

const GRID_DETAIL_PANELS_CLASS = 'MuiDataGrid-detailPanels';

export const useStickyMasterDetailPanel = (
  apiRef: DataGridProps['apiRef'],
  enableSticky?: boolean
) => {
  const getRootWidth = React.useCallback(() => {
    const dimensions = apiRef?.current.getRootDimensions?.();
    return dimensions?.viewportInnerSize.width;
  }, [apiRef]);

  const updateDetailPanelsStyles = React.useCallback(
    (e?: Event) => {
      const rootEl = apiRef?.current?.rootElementRef?.current;
      const detailPanelsEl = rootEl?.querySelector(
        `.${GRID_DETAIL_PANELS_CLASS}`
      ) as HTMLDivElement;
      if (!rootEl || !detailPanelsEl) return;

      const width = getRootWidth();
      if (!width) return;

      detailPanelsEl.style.position = 'sticky';
      detailPanelsEl.style.left = '0px';
      detailPanelsEl.style.zIndex = '1';
      detailPanelsEl.style.width = `${width}px`;
    },
    [apiRef, getRootWidth]
  );

  const handleViewportInnerSizeChange = React.useCallback(
    () => updateDetailPanelsStyles(),
    [updateDetailPanelsStyles]
  );

  React.useEffect(() => {
    if (!enableSticky) return;
    handleViewportInnerSizeChange();
    return apiRef?.current.subscribeEvent('viewportInnerSizeChange', handleViewportInnerSizeChange);
  }, [apiRef, enableSticky, handleViewportInnerSizeChange]);
};
