import { ChatMessage } from "../services/feedService";
import { ChatFlowMessage } from "../hooks/useChatFlow";

const normalizeBooleanValue = (value: any): boolean => {
  if (value === true || value === "true" || value === "True") return true;
  if (value === false || value === "false" || value === "False") return false;
  return false;
};

export const mapApiChatsToUiMessages = (chats: ChatMessage[]): ChatFlowMessage[] => {
  const uiMessages: ChatFlowMessage[] = [];

  chats.forEach((chat, index) => {
    // Filter out "شروع" question - don't show it
    const isStartQuestion = chat.question && chat.question.trim().toLowerCase() === "شروع";

    // Only show non-empty questions that are not "شروع"
    if (chat.question && chat.question.trim() && !isStartQuestion) {
      uiMessages.push({
        id: `user-${index}`,
        type: "user",
        content: chat.question,
        mediaType: "text",
        timestamp: new Date(),
        datetime1: chat.datetime1,
      });
    }

    // Always show answers (even if question was "شروع")
    if (chat.answer && chat.answer.trim()) {
      uiMessages.push({
        id: `bot-${index}`,
        type: "bot",
        content: chat.answer,
        mediaType: "text",
        timestamp: new Date(),
        datetime1: chat.datetime1,
      });
    }
  });

  // Process last chat for actions and is_mission_end
  if (chats.length > 0 && uiMessages.length > 0) {
    const lastChat = chats[chats.length - 1];

    // Find the last bot message in the UI messages
    let lastBotMessageIndex = -1;
    for (let i = uiMessages.length - 1; i >= 0; i--) {
      if (uiMessages[i].type === "bot") {
        lastBotMessageIndex = i;
        break;
      }
    }

    if (lastBotMessageIndex !== -1) {
      let buttons: Array<{ id: string; label: string; action: string }> | undefined = undefined;

      // Build action buttons from multi_choice
      if (lastChat.actions && lastChat.actions.length > 0 && lastChat.actions[0].multi_choice) {
        buttons = lastChat.actions[0].multi_choice.map((label, index) => ({
          id: `action-init-${index}`,
          label: label,
          action: `multi_choice_${index}`,
        }));
      }

      // Add mission end button if applicable
      if (normalizeBooleanValue(lastChat.is_mission_end) === true) {
        if (!buttons) buttons = [];
        buttons.push({
          id: "submit-challenge-init",
          label: "🎯 رفتن به مرحله بعد و ثبت ماموریت",
          action: "submit-challenge",
        });
      }

      // Attach buttons to the last bot message
      if (buttons && buttons.length > 0) {
        uiMessages[lastBotMessageIndex].buttons = buttons;
      }
    }
  }

  return uiMessages;
};
