import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useState, useRef, useEffect } from "react";
import { getTopicConfig } from "../../config/topicConfig";
import { useMissionSession } from "../../hooks/useMissionSession";
import { useChatFlow } from "../../hooks/useChatFlow";
import { mapApiChatsToUiMessages } from "../../utils/chatbotMapper";
import { getChatbotBackTarget } from "../../utils/chatbotNavigation";
import { FeedHeader } from "./feed/FeedHeader";
import { AppBackground } from "./shared/AppBackground";
import { ChatMessageList, ChatMessageListRef } from "./chatbot/ChatMessageList";
import { ChatInputBar } from "./chatbot/ChatInputBar";
import { usePageTracking } from "../../hooks/usePageTracking";
import { backgroundImages } from "../../config/backgroundConfig";

export function ChatbotPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { topicId = "1" } = useParams<{ topicId: string }>();
  const topicConfig = getTopicConfig(topicId);
  const locationState = location.state as { selectedMissionTitle?: string } | null;

  usePageTracking(`چت‌بات ${topicConfig.title}`);

  const { sessionData, isLoading: isLoadingMission, error: missionError } =
    useMissionSession();
  const missionTitle =
    locationState?.selectedMissionTitle?.trim() ||
    localStorage.getItem("current_mission_title")?.trim() ||
    sessionData?.doingMission?.title?.trim();

  const [isMissionEnd, setIsMissionEnd] = useState(false);

  const { messages, setMessages, isSending, sendMessage, isTyping, typingText } =
    useChatFlow({
      workflowId: sessionData?.doingMission?.workflow_ID || null,
      onMissionEnd: () => setIsMissionEnd(true),
    });

  const hasAutoSentRef = useRef(false);
  const currentWorkflowIdRef = useRef<string | null>(null);
  const messageListRef = useRef<ChatMessageListRef>(null);

  useEffect(() => {
    if (sessionData?.chats && sessionData.chats.length > 0) {
      const uiMessages = mapApiChatsToUiMessages(sessionData.chats);
      setMessages(uiMessages);

      const lastChat = sessionData.chats[sessionData.chats.length - 1];
      if (
        lastChat?.is_mission_end === true ||
        lastChat?.is_mission_end === "True"
      ) {
        setIsMissionEnd(true);
      }
    }
  }, [sessionData, setMessages]);

  useEffect(() => {
    const workflowId = sessionData?.doingMission?.workflow_ID;

    if (!workflowId) return;

    if (currentWorkflowIdRef.current !== workflowId) {
      currentWorkflowIdRef.current = workflowId;
      hasAutoSentRef.current = false;
    }

    if (hasAutoSentRef.current) return;

    const chats = sessionData?.chats || [];

    if (chats.length === 0) {
      hasAutoSentRef.current = true;
      sendMessage("شروع", { skipUserMessage: true });
    }
  }, [sessionData?.doingMission?.workflow_ID, sessionData?.chats, sendMessage]);

  const handleButtonClick = (buttonId: string, action: string) => {
    if (action === "submit-challenge") {
      navigate(`/submit/${topicId}`, {
        state: {
          doingMission: sessionData?.doingMission,
        },
      });
      return;
    }

    if (action.startsWith("multi_choice_")) {
      const message = messages.find((msg) =>
        msg.buttons?.some((btn) => btn.id === buttonId),
      );

      if (message) {
        const button = message.buttons?.find((btn) => btn.id === buttonId);
        if (button) {
          sendMessage(button.label);
        }
      }
    }
  };

  const handleBack = () => {
    const target = getChatbotBackTarget(topicId);
    navigate(target);
  };

  if (isLoadingMission) {
    return (
      <div className="relative h-[100dvh] w-full overflow-hidden">
        <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.chatbot} />
        <div className="relative z-10 flex h-full items-center justify-center text-center text-white">
          <div>
            <div className="mx-auto mb-3 h-10 w-10 animate-spin rounded-full border-4 border-[#ffd6f0]/30 border-t-[#ff79cf]" />
            <p className="text-base font-bold">در حال بارگذاری...</p>
          </div>
        </div>
      </div>
    );
  }

  if (missionError) {
    return (
      <div className="relative h-[100dvh] w-full overflow-hidden">
        <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.chatbot} />
        <div className="relative z-10 flex h-full items-center justify-center px-4 text-center text-white">
          <div>
            <p className="text-base text-red-400">{missionError}</p>
            <button
              onClick={handleBack}
              className="mt-3 rounded-lg bg-white/20 px-5 py-1.5 text-sm transition hover:bg-white/30"
            >
              بازگشت
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="relative h-[100dvh] w-full overflow-hidden">
      <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.chatbot} />

      <div className="relative z-10 mx-auto grid h-full w-full max-w-md grid-rows-[auto_minmax(0,1fr)_auto]">
        <div className="shrink-0">
          <FeedHeader
            topicTitle={missionTitle || topicConfig.title}
            subtitle={missionTitle ? topicConfig.title : undefined}
            onBack={handleBack}
          />
        </div>

        <main
          className="min-h-0 overflow-y-auto px-3 pb-2"
          style={{
            maskImage: "linear-gradient(to bottom, transparent 0%, black 48px)",
            WebkitMaskImage:
              "linear-gradient(to bottom, transparent 0%, black 48px)",
            scrollbarWidth: "none",
            msOverflowStyle: "none",
          }}
        >
          <div className="pt-8">
            <ChatMessageList
              ref={messageListRef}
              messages={messages}
              onButtonClick={handleButtonClick}
              isTyping={isTyping}
              typingText={typingText}
            />
          </div>
        </main>

        <footer
          className="shrink-0"
          style={{
            paddingBottom: "calc(env(safe-area-inset-bottom, 0px) + 12px)",
          }}
        >
          <div className="px-3 pt-2">
            <ChatInputBar
              onSendMessage={sendMessage}
              disabled={isSending || isTyping}
            />
          </div>
        </footer>
      </div>

      <style>{`
        main::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </div>
  );
}
