"use client";
import React, { useEffect, useState, useRef } from "react";
import Cookies from "js-cookie";
import { useAppSelector, useAppDispatch } from "@/app/hooks/hooks";
import useApiPost from "@/app/hooks/postData";
import { useRouter } from "next/navigation";
import { ClipLoader } from "react-spinners";
import { hideModal } from "@/app/store/Slice/modalSlice";
import { setUserId } from "@/app/store/Slice/SetUserIdForChatOpen";
import { useGetMyAllFollowingQuery } from "@/app/store/api/GetMyFollowing";
import { useGetAllStoryQuery } from "@/app/store/api/GetStoryByUser";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";
import { useGetAllUsersQuery } from "../../store/api/AllUsersList";
import { 
  setFollowedUsers,
  toggleFollow
} from "@/app/store/Slice/MyFollowingSlice";
function TaggedPeopleInPostList() {
  const { postId } = useAppSelector((state) => state.taggedPost);
  const isPostTagPeopleModalVisible = useAppSelector(
    (state) => state.modals.PostTagPeople
  );
  const token = Cookies.get("Snapta_auth_token");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { data: UsersData, refetch: refetchUsers } = useGetAllUsersQuery({ token: token || "" });
  const { data: FollowingData, refetch: refetchFollowing } = useGetMyAllFollowingQuery({ token: token || "" });
  const { refetch: StoryRefetch } = useGetAllStoryQuery({ token: token || "" });
  const { postData, loading } = useApiPost();
  
  // Get followed users from Redux
  const followedUsers = useAppSelector((state: any) => state.followStats?.followedUsers || {});
  
  const [taggedUsers, setTaggedUsers] = useState<any[]>([]);
  const [followLoadingStates, setFollowLoadingStates] = useState<Record<string, boolean>>({});
  
  // Initialize followed users from FollowingData (like Discover component)
  useEffect(() => {
    if (FollowingData?.follower) {
      const followedUserIds = FollowingData.follower.reduce(
        (account: { [key: string]: boolean }, follow: any) => {
          account[follow.follow_user_id] = true;
          return account;
        },
        {} as { [key: string]: boolean }
      );
      dispatch(setFollowedUsers(followedUserIds));
    }
  }, [FollowingData, dispatch]);

  // Fetch tagged users
  useEffect(() => {
    if (postId) {
      fetchTaggedUsers();
    }
  }, [postId]);

  const fetchTaggedUsers = async () => {
    try {
      const response = await postData("/all_tag_post_user", { post_id: postId });
      if (response?.post) {
        console.log("Tagged users:", response.post);
        setTaggedUsers(response.post);
      }
    } catch (error) {
      console.error("Error fetching tagged users:", error);
    }
  };

 const handleFollow = async (userId: string) => {
  if (followLoadingStates[userId]) return;
  
  setFollowLoadingStates(prev => ({ ...prev, [userId]: true }));
  
  // Use Redux action for optimistic update
  dispatch(toggleFollow(userId));

  try {
    const response = await postData("/follow", { to_user: userId });
    showSuccessToast(response?.message);
    refetchFollowing();
    StoryRefetch();
    refetchUsers();
    
  } catch (error: any) {
    // Revert optimistic update on error
    dispatch(toggleFollow(userId));
    showErrorToast(error?.data?.message || "Failed to follow/unfollow", "Something went wrong.");
  } finally {
    setFollowLoadingStates(prev => ({ ...prev, [userId]: false }));
  }
};

  const handleUsernameClick = (user: any) => {
    if (!user?.username) {
      console.error("Username missing:", user);
      return;
    }
    dispatch(hideModal("PostTagPeople"));
    router.push(`/Profile/${user.username}`);
  };

  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleOutsideClick = (e: MouseEvent) => {
      if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
        dispatch(hideModal("PostTagPeople"));
      }
    };

    if (isPostTagPeopleModalVisible) {
      document.addEventListener("mousedown", handleOutsideClick);
    }

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
    };
  }, [isPostTagPeopleModalVisible, dispatch]);

  if (!isPostTagPeopleModalVisible) return null;

  return (
    <div className="bg-[var(--modal-color)] border border-[var(--border-color)] shadow-xl rounded-lg relative w-[320px] mx-auto">
      {/* Cross Icon */}
      <div className="relative flex items-center justify-center border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] py-2">
        {/* Close Button */}
        <button
          onClick={() => dispatch(hideModal("PostTagPeople"))}
          className="absolute left-4 text-[20px] text-[var(--text-primary)] leading-none"
        >
          ×
        </button>

        {/* Middle Wrapper */}
        <div
          className="flex flex-col items-center justify-center"
          onClick={(e) => e.stopPropagation()}
        >
          <h2 className="text-[var(--text-primary)] font-medium text-[16px]">
            Tagged People
          </h2>
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center items-center w-full py-4">
          <ClipLoader size={20} color="#452B7A" />
        </div>
      ) : (
        <div className="max-h-72 w-full overflow-y-auto px-2">
          {taggedUsers.length > 0 ? (
            taggedUsers.map((tag, index) => {
              const isFollowing = followedUsers[tag?.user_id];
              const isLoading = followLoadingStates[tag?.user_id];
              
              return (
                <div
                 key={`${tag.user_id}_${index}`}
                  className="flex justify-between items-center py-2 w-full"
                >
                  <div className="flex gap-4 flex-1">
                    <img
                      src={tag?.profile_pic || "/assets/default_user.png"}
                      alt="Profile"
                      className="profileimageborderocolor h-12 w-12 object-cover rounded-full"
                    />
                    <div className="py-1">
                      <button>
                        <p
                          className="font-gilroy_semibold text-[var(--text-primary)] font-semibold text-sm text-left cursor-pointer"
                          onClick={() => handleUsernameClick(tag)}      
                        >
                          {tag?.first_name} {tag?.last_name}
                        </p>
                        <p className="text-[#747474] text-left font-gilroy_md text-sm">
                          {tag?.username}
                        </p>
                      </button>
                    </div>
                  </div>

                  <button
                    className={`rounded-xl font-gilroy_semibold text-[12px] h-fit w-[80px] py-1.5 transition-all duration-300 active:scale-95 ${
                      isFollowing
                        ? "text-[#341F60] dark:text-[var(--text-primary)] bg-transparent border border-[#341F60] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] hover:bg-[color-mix(in_srgb,var(--text-primary),transparent_95%)]"
                        : "bg-gradient-custom text-white border border-transparent hover:opacity-90"
                    }`}
                    disabled={isLoading}
                    onClick={() => handleFollow(tag?.user_id)}
                  >
                    {isLoading ? (
                      <ClipLoader size={12} color={isFollowing ? "#341F60" : "#FFFFFF"} />
                    ) : (
                      isFollowing ? "Following" : "Follow"
                    )}
                  </button>
                </div>
              );
            })
          ) : (
            <p className="text-gray-500 text-sm text-center mt-2">
              No tagged people
            </p>
          )}
        </div>
      )}
    </div>
  );
}

export default TaggedPeopleInPostList;