import { useAtomValue } from 'jotai';
import { pageVariantInfoAtom } from 'src/atoms/app';
import { useAmplitude } from 'src/contexts/amplitudeContext';
import { PageVariantInfo } from 'src/contexts/pageContext/types';
import { v4 as uuid } from 'uuid';
import { INTERACTION_TYPE_CLASS, InternalWidgetInteraction, WidgetInteraction } from './types';
import { extractPageContext } from './utils';

const getInteractionId = () => uuid();

export const useWidgetInteraction = () => {
  const { trackEvent } = useAmplitude();
  const variantInfo = useAtomValue(pageVariantInfoAtom);

  const trackWidgetInteraction = (props: WidgetInteraction) => {
    if (props.trigger) {
      // eslint-disable-next-line no-param-reassign
      props.trigger.interaction_id = props.trigger.interaction_id || getInteractionId();
      props.trigger.interaction_class =
        props.trigger.interaction_class || INTERACTION_TYPE_CLASS[props.trigger.widget_interaction];
    }

    const eventProps = {
      ...props,
      context: extractPageContext(variantInfo as PageVariantInfo),
    } as InternalWidgetInteraction;

    trackEvent({
      eventName: props.eventName,
      eventProps: { ...eventProps },
    });
  };

  return {
    trackWidgetInteraction,
    getInteractionId,
  };
};
