import { atom } from 'jotai';
import { Message, MessageType } from 'src/application/models';
import {
  messagesAtom,
  replyEventCategoryAtom,
  userHasRepliedAtom,
  userQueryAtom,
} from 'src/atoms/chat';
import { UserEventCategory } from '@spiffy-ai/commerce-api-client';
import { SpiffyMetricsEventName } from 'src/services/amplitudeService/amplitudeService';
import { amplitudeTrackEventAtom } from 'src/atoms/amplitude/amplitudeTrackEventAtom';
import { queueUserEventAtom } from './messageQueue';

type HandleReplyParams = {
  message: Message;
  userTyped: boolean;
};

export const handleReplyAtom = atom(null, (get, set, { message, userTyped }: HandleReplyParams) => {
  if (message.type !== MessageType.QueryTyped) {
    return;
  }

  const trackEvent = get(amplitudeTrackEventAtom);
  const queryTyped = message.metadata.content;

  set(replyEventCategoryAtom, UserEventCategory.QueryTyped);
  set(userQueryAtom, queryTyped);
  set(messagesAtom, [...get(messagesAtom), [message]]);
  set(userHasRepliedAtom, true);
  set(queueUserEventAtom, {
    eventId: message.id,
    createdAt: message.createdAt,
    category: UserEventCategory.QueryTyped,
    attributes: {
      query: queryTyped,
    },
  });

  if (trackEvent) {
    trackEvent({
      eventName: SpiffyMetricsEventName.ChatUserMessageInput,
      eventProps: {
        message_id: message.id,
        message_role: message.role,
        message_type: message.type,
        message_metadata: {
          content: message?.metadata?.content, // Removed amplitudeSafeString
          created_at: message.createdAt,
          user_typed: userTyped,
        },
      },
      alsoSendToGoogleAnalytics: true,
    });
  }
});
