import React, { useEffect } from 'react';
import {
  useFormPageContext,
  useWixPatternsContainer,
} from '@wix/bex-core/react';
import { getAnchorParam } from '@wix/bex-utils';

export function useAutoScrollOnLoad(
  scrollToItem: React.MutableRefObject<(() => void) | undefined>,
  doesItemExist: React.MutableRefObject<(() => boolean) | undefined>,
) {
  const { showToast, translate: t } = useWixPatternsContainer();
  const pageState = useFormPageContext();

  useEffect(() => {
    const pageStatus = pageState?.initTask?.status;

    if (!pageStatus.isLoading && !pageStatus.isIdle) {
      const anchorName = getAnchorParam();

      if (anchorName) {
        if (doesItemExist.current?.()) {
          scrollToItem.current?.();
        } else {
          showToast?.({
            message: t('cairo.settings.search.anchor-doesnt-exist.error', {
              anchorName,
            }),
            type: 'WARNING',
          });
        }
      }
    }
  }, [pageState?.initTask?.status]);
}
