import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { observer } from 'mobx-react-lite';
import {
  ScrollableContentContext,
  useScrollableContentContext,
} from '../../providers';

export interface ToolbarCollectionContentAutoSizerProps {
  children: ReactNode;
}

function _ToolbarCollectionContentAutoSizer(
  props: ToolbarCollectionContentAutoSizerProps,
) {
  const { children } = props;
  const { scrollableContentRef } = useScrollableContentContext();
  const internalScrollableContentRef = useRef<HTMLElement | null>(null);

  const [scrollableContentContextValue] = useState(() => ({
    scrollableContentRef: internalScrollableContentRef,
  }));

  const toolbar = useToolbarCollectionContext();
  const { internalScroll, collection } = toolbar;

  useEffect(() => {
    return toolbar.itemsContentRect.init({
      scrollElement: scrollableContentRef.current,
    });
  }, []);

  let child = (
    <div
      data-hook="toolbar-collection-content-auto-sizer"
      style={{
        height: '100%',
        width: '100%',
        overflowY: internalScroll ? 'auto' : undefined,
        overflowAnchor: 'none',
      }}
      ref={(el) => {
        toolbar.itemsContentRect.element = el;
        if (internalScroll) {
          internalScrollableContentRef.current = el;
          collection.scrollableContent = el;
        }
      }}
    >
      {children}
    </div>
  );

  if (internalScroll) {
    child = (
      <ScrollableContentContext.Provider value={scrollableContentContextValue}>
        {child}
      </ScrollableContentContext.Provider>
    );
  }

  return child;
}

export const ToolbarCollectionContentAutoSizer = observer(
  _ToolbarCollectionContentAutoSizer,
);
