import { useAtomValue } from 'jotai';
import { RefObject, useEffect, useRef } from 'react';
import { pageVariantInfoAtom } from 'src/atoms/app';
import { useAmplitude } from 'src/contexts/amplitudeContext/amplitudeContext';
import { PageVariantInfo } from 'src/contexts/pageContext/types';
import { useIntersection } from 'src/hooks/Intersection/useIntersection';
import { extractPageContext } from 'src/hooks/WidgetInteraction/utils';
import {
  EnviveMetricsEventName,
  SpiffyMetricsEventName,
} from 'src/services/amplitudeService/amplitudeService';

/**
 * Tracks a component and logs `SpiffyMetricsEventName.ChatComponentVisible` when visible.
 *
 * @param element - The element to track visibility of.
 * @param eventProps - Properties to include with the event.
 * @param rootMargin - Root margin for the intersection observer (defaults to 0px).
 * @param enabled - Whether tracking is enabled (defaults to true).
 */
export const useTrackComponentVisibleEvent = (
  element: RefObject<HTMLElement>,
  eventProps?: Record<string, unknown>,
  rootMargin: string = '0px',
  enabled: boolean = true,
): { isVisible: boolean } => {
  const isVisible = useIntersection(element, rootMargin);
  const hasTrackedEvent = useRef(false);
  const { trackEvent } = useAmplitude();
  const variantInfo = useAtomValue(pageVariantInfoAtom);

  useEffect(() => {
    console.debug('[useTrackComponentVisibleEvent] effect ran', {
      enabled,
      isVisible,
      hasTrackedEvent: hasTrackedEvent.current,
      eventProps,
    });

    if (!enabled) {
      console.debug('[useTrackComponentVisibleEvent] skipped — enabled is false');
      return;
    }
    if (hasTrackedEvent.current) {
      console.debug('[useTrackComponentVisibleEvent] skipped — event already tracked');
      return;
    }
    if (!isVisible) {
      console.debug('[useTrackComponentVisibleEvent] skipped — element not visible');
      return;
    }

    console.debug('[useTrackComponentVisibleEvent] firing tracking events', eventProps);
    trackEvent({
      eventName: SpiffyMetricsEventName.ChatComponentVisible,
      eventProps,
    });
    trackEvent({
      eventName: EnviveMetricsEventName.WidgetRendered,
      eventProps: {
        ...eventProps,
        trigger: {
          widget: eventProps?.widget_type,
        },
        context: variantInfo ? extractPageContext(variantInfo as PageVariantInfo) : null,
      },
    });
    hasTrackedEvent.current = true;
  }, [enabled, isVisible, eventProps, trackEvent]);
  return { isVisible };
};
