"use client";
import React, { useEffect, useState } from "react";
import { useAppSelector } from "../hooks/hooks";
import useApiPost from "../hooks/postData";
import ReelCommentModal from "../Explore/Reel_Comment";
import { ClipLoader } from "react-spinners";
import { showErrorToast } from "../components/Toast/ErrorToast";
import { useRouter, useParams } from "next/navigation";

function ReelDetail() {
  const router = useRouter();
  const params = useParams();
  const { postData } = useApiPost();
  const reelId = params.id as string;
  const reelIdFromRedux = useAppSelector((state) => state.ReelId?.id);
  const finalReelId = reelId || reelIdFromRedux;

  const [reelDetails, setReelDetails] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isMuted, setIsMuted] = useState(false);
  const [previousUrl, setPreviousUrl] = useState<string>("");

  useEffect(() => {
    // Store current URL for restoration when component mounts
    const currentPath = window.location.pathname + window.location.search;
    setPreviousUrl(currentPath);
    
    // Only save to localStorage if we're not already on the Reels/[id] page
    if (!currentPath.includes('/Reels/')) {
      localStorage.setItem("modalRedirectUrl", currentPath);
    }
  }, []);

  useEffect(() => {
    if (finalReelId) {
      fetchReelDetails();
    }
  }, [finalReelId]);

  const handleClose = () => {
    // Restore URL when closing
    if (previousUrl) {
      window.history.pushState({}, '', previousUrl);
    }
    
    // Get redirect URL from localStorage or fallback
    const savedRedirectUrl = localStorage.getItem("modalRedirectUrl");
    const loginRedirectUrl = localStorage.getItem("redirectAfterLogin");
    
    // Prioritize modalRedirectUrl, then loginRedirectUrl, then fallback
    if (savedRedirectUrl && savedRedirectUrl !== window.location.pathname) {
      router.push(savedRedirectUrl);
    } else if (loginRedirectUrl && loginRedirectUrl !== window.location.pathname) {
      router.push(loginRedirectUrl);
    } else {
      // For deep links, try to determine a better fallback
      const isDeepLink = document.referrer === "" || 
                       !document.referrer.includes(window.location.origin) ||
                       window.location.search.includes("modal=true");
      
      if (isDeepLink) {
        
        router.push("/Explore");
      } else {
        router.push("/Reels");
      }
    }
    
    // Clear the saved redirect URLs
    localStorage.removeItem("modalRedirectUrl");
    localStorage.removeItem("redirectAfterLogin");
  };

  const fetchReelDetails = async () => {
    try {
      setIsLoading(true);

      const response = await postData("/get_user_post_details", {
        post_id: finalReelId,
      });

      console.log("Reel details response:", response);

      if (response?.post_details) {
        setReelDetails(response.post_details);
      } else {
        showErrorToast("Reel not found", "The reel may have been deleted.");
        handleClose();
      }
    } catch (error) {
      console.error("Error fetching reel:", error);
      showErrorToast("Failed to load reel", "Something went wrong.");
      handleClose();
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-black">
        <ClipLoader color="white" size={40} />
      </div>
    );
  }

  if (!reelDetails) {
    return null;
  }

  const videoUrl = reelDetails.post_videos?.[0]?.url || "";

  return (
    <ReelCommentModal
      videoSrc={videoUrl}
      postId={finalReelId || ""}
      isMuted={isMuted}
      onMuteToggle={setIsMuted}
      onClose={handleClose}
      onCommentSuccess={() => {}}
    />
  );
}

export default ReelDetail;