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

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;
  isTyping?: boolean;
}

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 requestIdRef = useRef(0);
  const isMountedRef = useRef(true);
  const typingIntervalRef = useRef<NodeJS.Timeout | null>(null);

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

    const displayMessage = messageText.trim();
    const normalizedMessage = displayMessage.replace(/\r?\n+/g, " ").trim();

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

    const currentRequestId = ++requestIdRef.current;
    const serverMessage = normalizedMessage;

    try {
      setIsSending(true);

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

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

      const botMessageId = `bot-${Date.now()}`;
      const botTimestamp = new Date();
      const botDatetime = botTimestamp.toLocaleString("fa-IR");

      // Create a real bot message immediately and keep typing inside this same message
      setMessages((prev) => [
        ...prev,
        {
          id: botMessageId,
          type: "bot",
          content: "",
          mediaType: "text",
          timestamp: botTimestamp,
          datetime1: botDatetime,
          isTyping: true,
        },
      ]);

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

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

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

        if (typingIntervalRef.current) {
          clearInterval(typingIntervalRef.current);
        }

        // Build action buttons once, attach after typing completes
        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}`,
          }));
        }

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

          if (onMissionEnd) {
            onMissionEnd();
          }
        }

        let index = 0;
        const fullText = response.message;

        typingIntervalRef.current = setInterval(() => {
          if (!isMountedRef.current || currentRequestId !== requestIdRef.current) {
            if (typingIntervalRef.current) {
              clearInterval(typingIntervalRef.current);
              typingIntervalRef.current = null;
            }
            return;
          }

          if (index < fullText.length) {
            const nextContent = fullText.slice(0, index + 1);
            setMessages((prev) =>
              prev.map((msg) =>
                msg.id === botMessageId
                  ? { ...msg, content: nextContent, isTyping: true }
                  : msg,
              ),
            );
            index++;
            return;
          }

          if (typingIntervalRef.current) {
            clearInterval(typingIntervalRef.current);
            typingIntervalRef.current = null;
          }

          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === botMessageId
                ? {
                    ...msg,
                    content: fullText,
                    isTyping: false,
                    buttons,
                  }
                : msg,
            ),
          );
        }, 30);
      } else {
        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === botMessageId
              ? {
                  ...msg,
                  content: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
                  isTyping: false,
                }
              : msg,
          ),
        );
      }
    } catch (error) {
      if (!isMountedRef.current || currentRequestId !== requestIdRef.current) {
        return;
      }

      setMessages((prev) =>
        prev.map((msg) =>
          msg.type === "bot" && msg.isTyping
            ? {
                ...msg,
                content: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
                isTyping: false,
              }
            : msg,
        ),
      );
    } finally {
      if (isMountedRef.current && currentRequestId === requestIdRef.current) {
        setIsSending(false);
      }
    }
  }, [workflowId, isSending, onMissionEnd]);

  return {
    messages,
    setMessages,
    isSending,
    sendMessage,
    isTyping: false,
    typingText: "",
  };
};
