import { useActiveItem, useFormRootPath, useItems } from '@/components/ra-forms/LongForm/Provider';
import { IItem } from '@/components/ra-forms/LongForm/types';
import { getChildren, isChild } from '@/components/ra-forms/LongForm/utils';
import { useCallback, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router';

function useIsActive(id: string): boolean {
  const activeItem = useActiveItem();
  if (activeItem === undefined) {
    return false;
  } else {
    return id === activeItem || isChild(id, activeItem);
  }
}

function useChildren(id?: string): Array<IItem> {
  const items = useItems();
  const children = useMemo(() => getChildren(id, items), [items, id]);

  return children;
}

function useNavigateForm(): (id: string) => void {
  const formRootPath = useFormRootPath();
  const { search } = useLocation();
  const navigate = useNavigate();
  const navigateSection = useCallback(
    (id: string) => {
      navigate(`${formRootPath}/${id}${search}`);
    },
    [formRootPath, navigate, search]
  );

  return navigateSection;
}

export { useChildren, useIsActive, useNavigateForm };
