import { useAtomValue } from 'jotai';
import { useEffect, useRef } from 'react';
import { useAmplitude } from 'src/contexts/amplitudeContext/amplitudeContext';
import { SpiffyMetricsEventName } from 'src/services/amplitudeService/amplitudeService';
import { hasParsedVariantInfoAtom, variantInfoAtom } from 'src/atoms/app/variant';

/**
 * Updates the default analytics properties whenever the variant info changes. This hook also
 * triggers any events that should be sent once per page visit.
 */
export const useUpdateAnalyticsProps = () => {
  const variantInfo = useAtomValue(variantInfoAtom);
  const hasInitialized = useRef(false);
  const hasParsedVariantInfo = useAtomValue(hasParsedVariantInfoAtom);
  const { trackEvent, setSupplementalDefaultProps } = useAmplitude();

  useEffect(() => {
    const variantInfoWithPrefix = Object.fromEntries(
      Object.entries(variantInfo).map(([key, value]) => [`variantInfo.${key}`, value]),
    );

    const defaultEventProperties: Record<string, unknown> = {
      page_variant: variantInfo.variant, // TODO: should be removed over time, after migration
      ...variantInfoWithPrefix,
    };

    // TODO: should be removed over time, after migration
    if (variantInfo.variant === 'pdp') {
      defaultEventProperties.product_id = variantInfo.productId;
    }

    // TODO: should be removed over time, after migration
    if (variantInfo.variant === 'plp') {
      defaultEventProperties.plp_id = variantInfo.plpId;
    }

    // TODO: should be removed over time, after migration
    if (variantInfo.variant === 'page_visit') {
      defaultEventProperties.page_visit_category = variantInfo.pageVisitCategory;
      defaultEventProperties.page_visit_url = variantInfo.url;
    }

    setSupplementalDefaultProps(defaultEventProperties);

    // put any events that should be sent once per page visit here
    if (!hasInitialized.current && hasParsedVariantInfo) {
      trackEvent({
        eventName: SpiffyMetricsEventName.BundleLoaded,
      });
      hasInitialized.current = true;
    }
  }, [variantInfo, hasParsedVariantInfo, trackEvent, setSupplementalDefaultProps]);
};
