import { TaskState } from '@wix/bex-core';
import {
  wixPatternsFullPageLoadCompletedSrc144Evid1001,
  wixPatternsPageInteractiveSrc144Evid1000,
} from '@wix/bex-core/bi';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useEffect } from 'react';

export const useEntityPageLoadReporting = ({
  startTime,
  withinRouter,
  isFetching,
  initTask,
}: {
  startTime: number;
  withinRouter: boolean;
  isFetching: boolean;
  initTask: TaskState<unknown>;
}) => {
  const getBIParams = () => {
    const loadingTime = Math.round(performance.now() - startTime);
    return {
      componentType: 'Entity',
      loadingTime,
      withinRouter,
      routerUsage: withinRouter,
    };
  };

  const { createBILogger } = useWixPatternsContainer();

  const reportBI = createBILogger({
    pageType: 'Entity',
  });

  const reportPageInteractive = () => {
    const params = getBIParams();
    reportBI(wixPatternsPageInteractiveSrc144Evid1000(params));
  };

  const reportPageFullyLoaded = () => {
    const params = getBIParams();
    reportBI(wixPatternsFullPageLoadCompletedSrc144Evid1001(params));
  };

  useEffect(() => {
    if (isFetching) {
      reportPageInteractive();
      return;
    }

    if (initTask.status.isSuccess) {
      reportPageFullyLoaded();
      return;
    }
  }, [isFetching, initTask.status.isSuccess]);
};
