"use client";

import React, { useEffect, useState } from "react";
import Cookies from "js-cookie";
import useApiPost from "../hooks/postData";
import toast from "react-hot-toast";
import Image from "next/image";
import NoPostGif from "../../../public/assets/NoPost.png";
import TextTranslate from "../utils/TextTranslate";
import { X } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import { hideModal } from "@/app/store/Slice/modalSlice";
import { useGetMyAllFollowingQuery } from "@/app/store/api/GetMyFollowing";
import { useGetAllStoryQuery } from "@/app/store/api/GetStoryByUser";
import { showSuccessToast } from "../components/Toast/SuccessToast";
import { showErrorToast } from "../components/Toast/ErrorToast";

function LikeModal() {
  const [visible, setVisible] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [likedUsers, setLikedUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [fetchingUserDetails, setFetchingUserDetails] = useState(false);
  
  // Store user details cache to avoid duplicate API calls
  const [userDetailsCache, setUserDetailsCache] = useState<{
    [key: string]: any;
  }>({});

  // ✅ Follow state
  const [followedUsers, setFollowedUsers] = useState<{
    [key: string]: boolean;
  }>({});

  const dispatch = useAppDispatch();
  const { postData } = useApiPost();
  const token = Cookies.get("Snapta_auth_token");

  // ✅ Get postId and contentType from Redux
  const { id: postId, post_type: contentType } = useAppSelector((state) => state.PostId);


  // ✅ APIs for follow sync
  const { data: FollowingData, refetch: refetchFollowing } =
    useGetMyAllFollowingQuery({ token: token || "" });

  const { refetch: StoryRefetch } = useGetAllStoryQuery({
    token: token || "",
  });

  // ✅ Set initial followed users
  useEffect(() => {
    if (FollowingData?.follower) {
      const followedUserIds = FollowingData.follower.reduce(
        (acc: any, follow: any) => {
          acc[follow.follow_user_id] = true;
          return acc;
        },
        {}
      );

      setFollowedUsers(followedUserIds);
    }
  }, [FollowingData]);

  // ✅ Function to fetch user details for a single user
  const fetchUserDetails = async (userId: string) => {
    // Check cache first
    if (userDetailsCache[userId]) {
      return userDetailsCache[userId];
    }

    try {
      const response = await postData("/second_user_profile", {
        to_user_id: userId,
      });
      
      if (response?.user_data) {
        const userDetails = {
          user_id: userId,
          username: response.user_data.username,
          first_name: response.user_data.first_name,
          last_name: response.user_data.last_name,
          profile_pic: response.user_data.profile_pic,
        };
        
        // Update cache
        setUserDetailsCache((prev) => ({
          ...prev,
          [userId]: userDetails,
        }));
        
        return userDetails;
      }
      return null;
    } catch (error) {
      console.error(`Error fetching details for user ${userId}:`, error);
      return null;
    }
  };

  // ✅ Fetch likes based on content type (post or reel)
  const fetchLikedUsers = async () => {
    if (!postId) return;

    setLoading(true);

    try {
      let res;
      
      // Check if it's a reel or post based on contentType
      if (contentType === "reel") {
        // Use reel API endpoint
        res = await postData("/reel_like_list", {
          reel_id: postId,
        });
      } else {
        // Use post API endpoint (default)
        res = await postData("/post_like_list", {
          post_id: postId,
        });
      }
      
      console.log("API Response:", res); // Debug log

      if (res?.status === "success") {
        const likeList = res?.post_like_list || res?.reel_like_list || [];
        
        if (likeList.length > 0) {
          setFetchingUserDetails(true);
          
          // Fetch complete details for each user
          const usersWithDetails = await Promise.all(
            likeList.map(async (like: any) => {
              const userId = like.user_id || like.id;
              
              // Fetch full user details
              const userDetails = await fetchUserDetails(userId);
              
              if (userDetails) {
                return userDetails;
              }
              
              // Fallback to existing data if fetch fails
              return {
                user_id: userId,
                username: like.username || like.user_name || "",
                first_name: like.first_name || "",
                last_name: like.last_name || "",
                profile_pic: like.profile_pic || "/assets/default_user.png",
              };
            })
          );
          
          setLikedUsers(usersWithDetails);
          setFetchingUserDetails(false);
        } else {
          setLikedUsers([]);
        }
      } else {
    showErrorToast("Failed to fetch likes" , );
      }
    } catch (err) {
      console.error(err);
      showErrorToast("Failed to fetch likes");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLikedUsers();
  }, [postId, contentType]); // Re-fetch when postId or contentType changes

  // ✅ Follow / Unfollow handler
  const handleFollow = async (userId: string) => {
    const isCurrentlyFollowing = followedUsers[userId];

    // Optimistic update
    setFollowedUsers((prev) => ({
      ...prev,
      [userId]: !isCurrentlyFollowing,
    }));

    try {
      const response = await postData("/follow", {
        to_user: userId,
      });

      showSuccessToast(response?.message);
      refetchFollowing();
      StoryRefetch();
    } catch (error: any) {
      // rollback
      setFollowedUsers((prev) => ({
        ...prev,
        [userId]: isCurrentlyFollowing,
      }));

showErrorToast("Failed to follow/unfollow");
    }
  };

  const filteredUsers = likedUsers.filter((user: any) =>
    user.username?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    `${user.first_name} ${user.last_name}`.toLowerCase().includes(searchTerm.toLowerCase())
  );

  if (!visible) return null;

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm z-[200] p-4">
      <div className="bg-[var(--modal-color)] rounded-3xl shadow-2xl w-full max-w-[420px] md:max-w-[550px] overflow-hidden pb-6 animate-in fade-in zoom-in duration-200">

        {/* Header */}
        <div className="relative flex items-center justify-center px-4 py-4 border-b border-[var(--border-color)]">
          <button
            onClick={() => {
              dispatch(hideModal("LikeModal"));
              setVisible(false);
            }}
            className="absolute left-6 text-[var(--text-primary)]/80 hover:text-[var(--text-primary)]"
          >
            <X size={24} />
          </button>
          <h2 className="text-[var(--text-primary)] font-gilroy_semibold font-bold text-[17px]">
            <TextTranslate text="Likes" />
          </h2>
        </div>

        {/* Search */}
        <div className="flex items-center px-4 sm:px-6 py-2 mb-2 border-b border-[var(--border-color)]">
          <img
            src="/assets/follower_search.png"
            className="w-4 h-4 mr-3 opacity-50 img-theme"
          />
          <input
            type="text"
            placeholder="Search users..."
            className="bg-transparent outline-none text-[var(--text-primary)] text-[14px] w-full py-1 placeholder:text-[var(--text-primary)]/30"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        {/* List */}
        <div className="max-h-[400px] overflow-y-auto theme-scrollbar">
          {loading || fetchingUserDetails ? (
            <div className="flex justify-center py-10 text-sm text-[var(--text-secondary)]">
              Loading...
            </div>
          ) : filteredUsers.length > 0 ? (
            filteredUsers.map((user: any) => (
              <div
                key={user.user_id}
                className="flex items-center justify-between px-4 sm:px-6 py-3 hover:bg-[color-mix(in_srgb,var(--text-primary),transparent_95%)]"
              >
                {/* LEFT SIDE */}
                <div className="flex items-center gap-3">
                  <img
                    src={user.profile_pic || "/assets/default_user.png"}
                    className="w-12 h-12 rounded-full object-cover border border-[var(--border-color)]"
                  />

                  <div className="flex flex-col">
                    {/* ✅ USERNAME (TOP - BOLD & LARGER) */}
                    <p className="text-[var(--text-primary)] font-gilroy_semibold font-bold text-[15px]">
                      {user.username}
                    </p>

                    {/* ✅ FULL NAME (BOTTOM - SECONDARY SHADE & SMALLER) */}
                    <p className="text-[var(--text-secondary)] text-[13px]">
                      {user.first_name} {user.last_name}
                    </p>
                  </div>
                </div>

                {/* RIGHT SIDE FOLLOW BUTTON */}
                <button
                  className={`rounded-xl font-gilroy_semibold text-[12px] h-fit w-[80px] py-1.5 transition-all duration-300 active:scale-95 ${
                    !followedUsers[user.user_id]
                      ? "bg-gradient-custom text-white border border-transparent"
                      : "text-[#341F60] dark:text-[var(--text-primary)] bg-transparent border border-[#341F60] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                  }`}
                  onClick={() => handleFollow(user.user_id)}
                >
                  {followedUsers[user.user_id] ? (
                    <TextTranslate text="Following" />
                  ) : (
                    <TextTranslate text="Follow" />
                  )}
                </button>
              </div>
            ))
          ) : (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <Image
                src={NoPostGif}
                alt="No likes"
                className="w-16 h-16 opacity-20 img-theme"
              />
              <p className="mt-4 text-[var(--text-secondary)] text-[14px]">
                <TextTranslate text="No likes yet" />
              </p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 sm:px-6 mt-4 -mb-3">
          <button
            onClick={() => {
              dispatch(hideModal("LikeModal"));
              setVisible(false);
            }}
            className="w-full py-2.5 bg-[#341F60] text-white rounded-xl font-bold"
          >
            <TextTranslate text="Done" />
          </button>
        </div>
      </div>
    </div>
  );
}

export default LikeModal;