import { useState, useEffect, useRef } from "react";
import { useSearchParams, useLocation } from "react-router-dom";
import { ChatMessage, DoingMission, startMission } from "../services/feedService";
import { useInbox } from "../app/context/InboxContext";

interface MissionSessionData {
  chats: ChatMessage[];
  doingMission: DoingMission | null;
  missionType: string;
}

interface UseMissionSessionResult {
  sessionData: MissionSessionData | null;
  isLoading: boolean;
  error: string | null;
}

export const useMissionSession = (): UseMissionSessionResult => {
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const { refreshInbox } = useInbox();

  const [sessionData, setSessionData] = useState<MissionSessionData | null>(() => {
    const locationState = location.state as any;
    if (locationState?.chats || locationState?.doingMission) {
      return {
        chats: locationState.chats || [],
        doingMission: locationState.doingMission || null,
        missionType: locationState.missionType || "",
      };
    }
    return null;
  });

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const isMountedRef = useRef(true);

  useEffect(() => {
    isMountedRef.current = true;

    const restoreMission = async () => {
      // اگر از location.state داده داشتیم، نیازی به restore نیست
      const locationState = location.state as any;
      if (locationState?.chats || locationState?.doingMission) {
        return;
      }

      // اگر sessionData قبلاً وجود داشت و چت‌ها نیست (مثلاً بعد از برگشت از submit)
      // یا اگر sessionData اصلاً وجود نداشت، باید restore کنیم
      const urlMissionId = searchParams.get("missionId");
      const urlMissionType = searchParams.get("missionType");
      const continueMode = searchParams.get("continueMode");

      let missionType: string | null = null;
      let missionId: string | null = null;

      if (continueMode === "true" && urlMissionId && urlMissionType) {
        missionType = urlMissionType;
        missionId = urlMissionId;

        localStorage.setItem("current_mission_type", missionType);
        localStorage.setItem("current_mission_id", missionId);
      } else {
        missionType = localStorage.getItem("current_mission_type");
        missionId = localStorage.getItem("current_mission_id");
      }

      if (!missionType || !missionId) {
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const response = await startMission(missionType, missionId);

        if (!isMountedRef.current) return;

        if (response.doing_mission?.workflow_ID) {
          localStorage.setItem("current_workflow_ID", response.doing_mission.workflow_ID);
        }

        await refreshInbox();

        setSessionData({
          chats: response.chats,
          doingMission: response.doing_mission,
          missionType,
        });
      } catch (err) {
        if (!isMountedRef.current) return;
        setError("خطا در بارگذاری ماموریت");
      } finally {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    };

    restoreMission();

    return () => {
      isMountedRef.current = false;
    };
  }, [location.pathname, searchParams, refreshInbox]);

  return {
    sessionData,
    isLoading,
    error,
  };
};
