import { useAtomValue, useSetAtom } from 'jotai';
import { ChatElementDisplayLocationV3 } from 'src/application/models';
import { chatAtom, chatOnToggleAtom } from 'src/atoms/chat';
import {
  EnviveMetricsEventName,
  SpiffyMetricsEventName,
  useAmplitude,
} from 'src/contexts/amplitudeContext/amplitudeContext';
import { useWidgetInteraction } from '../WidgetInteraction';
import { WidgetInteractionComponent, WidgetInteractionType } from '../WidgetInteraction/types';

export const useChatToggle = () => {
  const onToggle = useSetAtom(chatOnToggleAtom);
  const { isOpen } = useAtomValue(chatAtom);
  const { trackEvent } = useAmplitude();
  const { trackWidgetInteraction } = useWidgetInteraction();

  const toggle = (triggerLocation: ChatElementDisplayLocationV3, triggerId?: string) => {
    if (!isOpen) {
      trackWidgetInteraction({
        eventName: EnviveMetricsEventName.WidgetInteraction,
        trigger: {
          widget: WidgetInteractionComponent.FLOATING_BUTTON,
          widget_interaction: WidgetInteractionType.WIDGET_CLICKED,
        },
      });

      trackEvent({
        eventName: SpiffyMetricsEventName.ChatComponentExpanded,
        eventProps: {
          message_metadata: {
            trigger_location: triggerLocation,
            trigger_id: triggerId,
          },
        },
      });
    } else {
      trackWidgetInteraction({
        eventName: EnviveMetricsEventName.WidgetInteraction,
        trigger: {
          widget: WidgetInteractionComponent.FLOATING_BUTTON,
          widget_interaction: WidgetInteractionType.WIDGET_COLLAPSED,
        },
      });

      trackEvent({
        eventName: SpiffyMetricsEventName.ChatComponentCollapsed,
        eventProps: {
          message_metadata: {
            trigger_location: triggerLocation,
            trigger_id: triggerId,
          },
        },
      });
    }

    onToggle();
  };

  const openChat = (triggerLocation: ChatElementDisplayLocationV3, triggerId?: string) => {
    if (!isOpen) {
      toggle(triggerLocation, triggerId);
    }
  };

  const closeChat = (triggerLocation: ChatElementDisplayLocationV3, triggerId?: string) => {
    if (isOpen) {
      toggle(triggerLocation, triggerId);
    }
  };

  const onHover = () => {
    trackWidgetInteraction({
      eventName: EnviveMetricsEventName.WidgetInteraction,
      trigger: {
        widget: WidgetInteractionComponent.FLOATING_BUTTON,
        widget_interaction: WidgetInteractionType.WIDGET_HOVERED,
      },
    });
  };

  return {
    toggle,
    isOpen,
    openChat,
    closeChat,
    onHover,
  };
};
