import { useCallback, useEffect, useRef } from 'react';
import type { FiltersMap } from '@wix/bex-core';
import type { CellInteractionState } from '../../state/EditableTable/CellInteractionState';

/**
 * Clears cell focus when the user clicks outside the table container.
 *
 * Skips clearFocus() while isEditing=true so that portaled editors (date
 * picker, select dropdown, media manager) can take focus without causing the
 * cell to lose its editing state. Cell types that open external UI are
 * responsible for calling onStartEdit() before the modal opens (which sets
 * isEditing=true) and onCancel()/onCommit() when it closes.
 */
export function useClearFocusOnBlur<T, F extends FiltersMap>(
  cellInteraction: CellInteractionState<T, F>,
) {
  const blurFrameId = useRef(0);

  useEffect(() => {
    return () => cancelAnimationFrame(blurFrameId.current);
  }, []);

  const onFocus = useCallback(() => {
    cancelAnimationFrame(blurFrameId.current);
  }, []);

  const onBlur = useCallback(
    (e: React.FocusEvent<HTMLDivElement>) => {
      cancelAnimationFrame(blurFrameId.current);
      const container = e.currentTarget;

      blurFrameId.current = requestAnimationFrame(() => {
        if (container.contains(document.activeElement)) {
          return;
        }

        if (!cellInteraction.isEditing) {
          cellInteraction.clearFocus();
        }
      });
    },
    [cellInteraction],
  );

  return { onFocus, onBlur };
}
