import { useEffect, useRef } from 'react';

import { trackLoanSidebarItemViewed } from '../track';
import {
  getMicroloansEntryPath,
  shouldShowMicroloansInSidebar,
} from '../utils/microloansNav';

import { useCollaboratorStatus } from './useCollaboratorStatus';

export type UseMicroloansNavStateResult = {
  showInSidebar: boolean;
  entryPath: string;
  isReady: boolean;
};

export function useMicroloansNavState(): UseMicroloansNavStateResult {
  const hasTrackedSidebarItemViewedRef = useRef(false);
  const { hasOffer, hasActivePlan, hasFinishedPlans, isReady } =
    useCollaboratorStatus();

  const flags = { hasOffer, hasActivePlan, hasFinishedPlans };
  const showInSidebar = isReady ? shouldShowMicroloansInSidebar(flags) : false;
  const entryPath = getMicroloansEntryPath(flags);

  useEffect(() => {
    if (!isReady || !showInSidebar || hasTrackedSidebarItemViewedRef.current) {
      return;
    }
    hasTrackedSidebarItemViewedRef.current = true;
    trackLoanSidebarItemViewed();
  }, [isReady, showInSidebar]);

  return {
    showInSidebar,
    entryPath,
    isReady,
  };
}
