import { useFormContext } from 'react-hook-form';

import { type NewSessionFormValues } from 'src/pages/dashboard/Learning/Sessions/types';

const useValidateStep = () => {
  const { trigger } = useFormContext<NewSessionFormValues>();

  const validateStep = async (step: keyof NewSessionFormValues) => {
    const isValid = await trigger(step, { shouldFocus: true });

    if (!isValid) {
      requestAnimationFrame(() => {
        const active = document.activeElement as HTMLElement | null;
        if (active && typeof active.scrollIntoView === 'function') {
          active.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      });
    }

    return isValid ?? true;
  };

  return validateStep;
};

export default useValidateStep;
