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

function PostDetail() {
  const router = useRouter();
  const params = useParams();
  const { postData, loading } = useApiPost();
  const postId = params.id as string;
  const postIdFromRedux = useAppSelector((state) => state.PostId?.id);
  const finalPostId = postId || postIdFromRedux;
  const [postDetails, setPostDetails] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  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 Post/[id] page
    if (!currentPath.includes('/Post/')) {
      localStorage.setItem("modalRedirectUrl", currentPath);
    }
  }, []);

  useEffect(() => {
    if (finalPostId) {
      fetchPostDetails();
    }
  }, [finalPostId]);

  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) {
        // For deep links, default to Explore since that's where posts are typically viewed
        router.push("/Explore");
      } else {
        // For internal navigation, default to Home page
        router.push("/Home");
      }
    }
    
    // Clear the saved redirect URLs
    localStorage.removeItem("modalRedirectUrl");
    localStorage.removeItem("redirectAfterLogin");
  };

  useEffect(() => {
    if (postId) {
      fetchPostDetails();
    }
  }, [postId]);

  const fetchPostDetails = async () => {
    try {
      setIsLoading(true);
      const response = await postData("/get_user_post_details", {
        post_id: postId,
      });

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

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

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
      <ClipLoader color="var(--text-primary)" size={30} />
      </div>
    );
  }

  if (!postDetails) {
    return null;
  }

  // ✅ FIX: Properly extract image URLs - check both 'image' and 'post_image' arrays
  const images =
    postDetails.image?.map((img: any) => img.url) ||
    postDetails.post_image?.map((img: any) => img.url) ||
    [];

  console.log("Extracted images:", images);
  console.log("Post details structure:", postDetails);

  // If no images found, try to get video thumbnail
  if (images.length === 0 && postDetails.post_videos?.length > 0) {
    const videoThumbnails = postDetails.post_videos.map(
      (video: any) => video.thumbnail || video.url
    );

    console.log("Using video thumbnails:", videoThumbnails);

    return (
      <PostDetailModal
        images={videoThumbnails}
        postId={finalPostId || ""}
        onClose={handleClose}
      />
    );
  }

  if (images.length === 0) {
    showErrorToast(
      "No media found for this post",
      "The post may have been deleted."
    );
    handleClose();
    return null;
  }

  return (
    <PostDetailModal
      images={images}
      postId={finalPostId || ""}
      onClose={handleClose}
    />
  );
}

export default PostDetail;