import { UserEventCategory } from '@spiffy-ai/commerce-api-client/dist/models/UserEventCategory';
import { atom } from 'jotai';
import { SpiffyMetricsEventName } from 'src/services/amplitudeService/amplitudeService';
import {
  ChatElementDisplayLocationV3,
  FormSubmittedAttributes,
  Message,
  Suggestion,
  UserEvent,
} from 'src/application/models';
import { ChatElementDisplayLocation } from 'src/application/models/chatElementDisplayLocation';
import { SpiffyEventName } from 'src/application/models/events';

export const userHasRepliedAtom = atom<boolean>(false);
export const replyEventCategoryAtom = atom<UserEventCategory>(UserEventCategory.AppLoaded);
export const userQueryAtom = atom<string>();
export const suggestionAtom = atom<Suggestion | undefined>(undefined);
export const askQuestionBtnClickedAtom = atom<boolean>(false);
export const messagesAtom = atom<Message[][]>([]);
export const userEventsAtom = atom<UserEvent[]>([]);
export const suggestionsAtom = atom<Suggestion[]>([]);
export const suggestionsLoadingAtom = atom<boolean>(false);
export const responseStreamingAtom = atom<boolean>(false);
export const pendingResponseAtom = atom<boolean>(false);
export const initializedAtom = atom<boolean>(false);
export const chatIsOpenAtom = atom<boolean>(false);
export const requestFailureAtom = atom<boolean>(false);
export const formSubmitAtom = atom<FormSubmittedAttributes>();
export const listeningToSpeechAtom = atom<'start' | 'stop' | 'abort' | undefined>(undefined);
export const chatOnToggleAtom = atom(
  null,
  (
    get,
    set,
    triggerLocation?: ChatElementDisplayLocation | ChatElementDisplayLocationV3,
    track?: (eventName: SpiffyMetricsEventName, eventProps?: Record<string, unknown>) => void,
  ) => {
    const isOpen = get(chatIsOpenAtom);
    set(chatIsOpenAtom, !isOpen);

    if (!isOpen) {
      window.dispatchEvent(new CustomEvent(SpiffyEventName.WidgetOpen));
      track?.(SpiffyMetricsEventName.ChatComponentExpanded, {
        message_metadata: {
          trigger_location: triggerLocation,
        },
      });
    } else {
      window.dispatchEvent(new CustomEvent(SpiffyEventName.WidgetClose));
      track?.(SpiffyMetricsEventName.ChatComponentCollapsed);
    }
  },
);
