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

export function useAddRow<T, F extends FiltersMap>(
  state: EditableTableState<T, F>,
) {
  const firstEditableColId = state.editableColumns.find(
    (col) => col.editable !== false && !!col.setValue,
  )?.id;

  // Cached anchor so chained afterItemKey deps are avoided —
  // prepareItemsToMergeIntoPage reverses createdPatches, so chained anchors
  // would strand later items at the top of the table.
  const addItemAnchorRef = useRef<string | undefined>(undefined);

  const handleAddItem = useCallback(() => {
    state.onAddItemClick('Card CTA');

    // Refresh the anchor if it's missing or no longer in the current page
    // (e.g. after query/filter/pagination changes moved it off-page).
    const isAnchorStale =
      !addItemAnchorRef.current ||
      !state.keyedItems.some((ki) => ki.key === addItemAnchorRef.current);
    if (isAnchorStale) {
      addItemAnchorRef.current =
        state.keyedItems[state.keyedItems.length - 1]?.key;
    }
    const newKey = state.addItem(addItemAnchorRef.current);
    if (!newKey || !firstEditableColId) return;
    // RAF gives React one frame to render the new row before we try to focus it.
    requestAnimationFrame(() => {
      state.cellInteraction.startEdit(newKey, firstEditableColId, 'enter');
    });
  }, [state, firstEditableColId]);

  const showAddItemRow =
    !state.addItemDisabled && state.collection.initTask.status.isSuccess;

  return { showAddItemRow, handleAddItem };
}
