import { useAtomValue } from 'jotai';
import { useEffect, useRef } from 'react';
import { VariantTypeEnum } from 'src/application/models';
import { hasParsedVariantInfoAtom, variantInfoAtom } from 'src/atoms/app/variant';
import { EnviveMetricsEventName, useAmplitude } from 'src/contexts/amplitudeContext';
import { usePage } from 'src/contexts/pageContext';
import {
  FullPageSalesAgentVariantInfo,
  HomeVariantInfo,
  OtherVariantInfo,
  PDPPageVariantInfo,
  PLPPageVariantInfo,
  PageVariantInfo,
  VisitPageVariantInfo,
} from 'src/contexts/pageContext/types';

interface PageViewedContext {
  page_type: string;
  page_id: string;
}

export const extractPageViewedContext = (
  pageVariant: PageVariantInfo,
): PageViewedContext | null => {
  switch (pageVariant.variantType) {
    case VariantTypeEnum.Pdp:
      return {
        page_type: 'pdp',
        page_id: (pageVariant as PDPPageVariantInfo).productId,
      };
    case VariantTypeEnum.Plp:
      return {
        page_type: 'plp',
        page_id: (pageVariant as PLPPageVariantInfo).plpId,
      };
    case VariantTypeEnum.Home:
      return {
        page_type: 'homepage',
        page_id: (pageVariant as HomeVariantInfo).url,
      };
    case VariantTypeEnum.Other:
      return {
        page_type: 'other',
        page_id: (pageVariant as OtherVariantInfo).url,
      };
    case VariantTypeEnum.PageVisit:
      return {
        page_type: 'other',
        page_id: (pageVariant as VisitPageVariantInfo).url,
      };
    case VariantTypeEnum.FullPageSalesAgent:
      return {
        page_type: 'full_page_sales_agent',
        page_id: (pageVariant as FullPageSalesAgentVariantInfo).url,
      };
    default:
      return null;
  }
};

/**
 * Fires the [Envive] Page Viewed event once per page load when page context data is ready.
 *
 * This event captures page context information and is intended to eventually replace
 * the [Amplitude] Page Viewed event.
 */
export const usePageViewedEvent = () => {
  const hasFired = useRef(false);
  const { trackEvent } = useAmplitude();
  const { variantInfo: pageVariantInfo, isSupported, isLoading } = usePage();
  const variantInfo = useAtomValue(variantInfoAtom);
  const hasParsedVariantInfo = useAtomValue(hasParsedVariantInfoAtom);

  useEffect(() => {
    if (hasFired.current) {
      return;
    }

    if (isLoading || !hasParsedVariantInfo || !pageVariantInfo) {
      return;
    }

    const pageContext = extractPageViewedContext(pageVariantInfo);
    if (!pageContext) {
      return;
    }

    hasFired.current = true;

    trackEvent({
      eventName: EnviveMetricsEventName.PageViewed,
      eventProps: {
        'context.page_type': pageContext.page_type,
        'context.page_id': pageContext.page_id,
        // context.supported and context.ready both derive from isSupported (response.ready)
        // because the supportedEventAtom is not currently populated.
        'context.supported': isSupported,
        'context.ready': isSupported,
        'context.page_variant_id': variantInfo.variantId,
      },
    });
  }, [isLoading, isSupported, hasParsedVariantInfo, pageVariantInfo, variantInfo, trackEvent]);
};
