import { useScrollableContentContext } from '../../providers';
import { useEffect, useState } from 'react';
import { TableV2Props } from './TableV2';
import type { FiltersMap } from '@wix/bex-core';
import { usePageContext } from '@wix/bex-core/react';
import { TableDragAndDropState } from '../DragAndDrop/TableDragAndDropState';
import { useTagsBulkAssignUtils } from '../Tags/useTagsBulkAssignUtils';
import { runInAction } from 'mobx';

export function useTableSyncProps<T, F extends FiltersMap>(
  props: TableV2Props<T, F>,
) {
  const { state, scrollElement: scrollElementProp } = props;
  const { scrollableContentRef } = useScrollableContentContext();
  const { modalsContainerRef } = usePageContext();

  const [scrollElement, setScrollElement] = useState(
    () =>
      scrollElementProp ??
      (scrollableContentRef?.current as HTMLElement | undefined),
  );

  useState(() => {
    props.dragAndDrop?.setStateObject({
      state,
      modalsContainerRef,
    });
  });

  const collectionDragAndDropState = (
    state.tableDragAndDropState as TableDragAndDropState<T, F>
  )?.dragAndDrop;
  if (collectionDragAndDropState) {
    collectionDragAndDropState.dragAndDropCancel = props.dragAndDropCancel;
  }

  useTagsBulkAssignUtils({ state });

  useEffect(() => {
    const { collection } = state;

    const scrollableContent =
      scrollElementProp ?? scrollableContentRef?.current;

    if (scrollableContent) {
      setScrollElement(scrollableContent);

      runInAction(() => {
        collection.scrollableContent =
          scrollableContent instanceof HTMLElement
            ? scrollableContent
            : scrollableContent.current;
      });
    }

    return () => {
      runInAction(() => {
        collection.scrollableContent = null;
      });
    };
  }, [scrollElementProp]);

  return {
    scrollElement,
  };
}
