import { useState, useCallback, useRef } from "react";
import { sendChatMessage } from "../services/feedService";
import { useTypingMessage } from "./useTypingMessage";

export interface ChatFlowMessage {
  id: string;
  type: "user" | "bot";
  content: string;
  mediaType?: "text" | "image" | "audio" | "file" | "video";
  mediaUrl?: string;
  timestamp: Date;
  buttons?: Array<{ id: string; label: string; action: string }>;
  datetime1?: string;
  duration?: string;
}

interface UseChatFlowOptions {
  workflowId: string | null;
  onMissionEnd?: () => void;
}

interface UseChatFlowResult {
  messages: ChatFlowMessage[];
  setMessages: React.Dispatch<React.SetStateAction<ChatFlowMessage[]>>;
  isSending: boolean;
  sendMessage: (messageText: string, options?: { skipUserMessage?: boolean }) => Promise<void>;
  isTyping: boolean;
  typingText: string;
}

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 useChatFlow = ({ workflowId, onMissionEnd }: UseChatFlowOptions): UseChatFlowResult => {
  const [messages, setMessages] = useState<ChatFlowMessage[]>([]);
  const [isSending, setIsSending] = useState(false);
  const { isTyping, typingText, startTyping } = useTypingMessage();
  const requestIdRef = useRef(0);
  const isMountedRef = useRef(true);

  const sendMessage = useCallback(async (messageText: string, options?: { skipUserMessage?: boolean }) => {
    console.log("sendMessage called:", {
      messageText,
      workflowId,
      isSending,
      skipUserMessage: options?.skipUserMessage,
    });

    if (!messageText.trim() || !workflowId) {
      console.log("sendMessage aborted:", {
        hasMessage: !!messageText.trim(),
        hasWorkflowId: !!workflowId,
      });
      return;
    }
    if (isSending) {
      console.log("Already sending, skipping");
      return;
    }

    const currentRequestId = ++requestIdRef.current;
    const trimmedMessage = messageText.trim();

    try {
      setIsSending(true);

      // Add user message unless skipped (for auto-send "شروع")
      if (!options?.skipUserMessage) {
        const userMessage: ChatFlowMessage = {
          id: `user-${Date.now()}`,
          type: "user",
          content: trimmedMessage,
          mediaType: "text",
          timestamp: new Date(),
          datetime1: new Date().toLocaleString("fa-IR"),
        };

        if (isMountedRef.current && currentRequestId === requestIdRef.current) {
          setMessages((prev) => [...prev, userMessage]);
        }
      }

      // شروع typing indicator برای نشان دادن فکر کردن ربات (با متن خالی)
      startTyping("", () => {});

      // Call API
      const response = await sendChatMessage(trimmedMessage, workflowId);

      // Guard against stale requests
      if (!isMountedRef.current || currentRequestId !== requestIdRef.current) {
        return;
      }

      if (response.success && response.message) {
        const isMissionEnd = normalizeBooleanValue(response.is_mission_end);

        // شروع نمایش متن پاسخ با افکت typing (این کار typing dots قبلی را هم متوقف می‌کند)
        startTyping(response.message, () => {
          if (!isMountedRef.current || currentRequestId !== requestIdRef.current) {
            return;
          }

          // Build action buttons
          let buttons: Array<{ id: string; label: string; action: string }> | undefined = undefined;

          if (response.actions && response.actions.length > 0 && response.actions[0].multi_choice) {
            buttons = response.actions[0].multi_choice.map((label, index) => ({
              id: `action-${Date.now()}-${index}`,
              label: label,
              action: `multi_choice_${index}`,
            }));
          }

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

            if (onMissionEnd) {
              onMissionEnd();
            }
          }

          const botMessage: ChatFlowMessage = {
            id: `bot-${Date.now()}`,
            type: "bot",
            content: response.message!,
            mediaType: "text",
            timestamp: new Date(),
            datetime1: new Date().toLocaleString("fa-IR"),
            buttons: buttons,
          };

          setMessages((prev) => [...prev, botMessage]);
        });
      } else {
        // Show error message
        const errorMessage: ChatFlowMessage = {
          id: `bot-${Date.now()}`,
          type: "bot",
          content: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
          mediaType: "text",
          timestamp: new Date(),
          datetime1: new Date().toLocaleString("fa-IR"),
        };

        setMessages((prev) => [...prev, errorMessage]);
      }
    } catch (error) {
      if (!isMountedRef.current || currentRequestId !== requestIdRef.current) {
        return;
      }

      const errorMessage: ChatFlowMessage = {
        id: `bot-${Date.now()}`,
        type: "bot",
        content: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
        mediaType: "text",
        timestamp: new Date(),
        datetime1: new Date().toLocaleString("fa-IR"),
      };

      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      if (isMountedRef.current && currentRequestId === requestIdRef.current) {
        setIsSending(false);
      }
    }
  }, [workflowId, isSending, startTyping, onMissionEnd]);

  return {
    messages,
    setMessages,
    isSending,
    sendMessage,
    isTyping,
    typingText,
  };
};
