"use client";
import React, { useEffect, useState, useCallback } from "react";
import Cookies from "js-cookie";
import { useGetAllUsersQuery } from "../../store/api/AllUsersList";
import { useGetMyAllFollowingQuery } from "../../store/api/GetMyFollowing";
import useApiPost from "@/app/hooks/postData";
import { useRouter } from "next/navigation";
import { useGetAllStoryQuery } from "@/app/store/api/GetStoryByUser";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import TextTranslate from "@/app/utils/TextTranslate";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";
import { 
  setFollowingCount,
  setFollowedUsers,
  updateFollowStatus
} from "@/app/store/Slice/MyFollowingSlice";

function Discover() {
  const token = Cookies.get("Snapta_auth_token");
  const dispatch = useAppDispatch();
  const router = useRouter();
  
  // Local state for button loading states
  const [loadingUsers, setLoadingUsers] = useState<{ [key: string]: boolean }>({});
  
  // Select state
  const followingCount = useAppSelector((state: any) => state.followStats?.followingCount || 0);
  const followedUsers = useAppSelector((state: any) => state.followStats?.followedUsers || {});
  
  const {
    data: UsersData,
    isLoading,
    refetch: refetchUsers,
  } = useGetAllUsersQuery({ token: token || "" }); 
  
  const { data: FollowingData, refetch: refetchFollowing } =
    useGetMyAllFollowingQuery({ token: token || "" });

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

  const { postData } = useApiPost();

  // Function to sync follow status from API
  const syncFollowStatus = useCallback(async () => {
    try {
      const result = await refetchFollowing();
      if (result.data?.follower) {
        const followedUserIds = result.data.follower.reduce(
          (account: { [key: string]: boolean }, follow: any) => {
            const id = String(follow.follow_user_id);
            account[id] = true;
            return account;
          },
          {} as { [key: string]: boolean }
        );
        dispatch(setFollowedUsers(followedUserIds));
        dispatch(setFollowingCount(result.data.follower.length));
      }
    } catch (error) {
      console.error("Error syncing follow status:", error);
    }
  }, [dispatch, refetchFollowing]);

  // Initialize data from API
  useEffect(() => {
    if (FollowingData?.follower) {
      const followingCountValue = FollowingData.follower.length;
      dispatch(setFollowingCount(followingCountValue));
      
      const followedUserIds = FollowingData.follower.reduce(
        (account: { [key: string]: boolean }, follow: any) => {
          const id = String(follow.follow_user_id);
          account[id] = true; 
          return account;
        },
        {} as { [key: string]: boolean }
      );
      dispatch(setFollowedUsers(followedUserIds));
    }
  }, [FollowingData, dispatch]);

  const handleFollow = async (userId: any) => {
    const stringId = String(userId);
    
    // Set loading state for this button
    setLoadingUsers(prev => ({ ...prev, [stringId]: true }));
    
    const isCurrentlyFollowing = followedUsers[stringId];
    
    // Optimistic UI update - toggle immediately
    dispatch(updateFollowStatus({ 
      userId: stringId, 
      isFollowing: !isCurrentlyFollowing 
    }));

    try {
      const response = await postData("/follow", { to_user: stringId });
      showSuccessToast(response?.message);
      
      // IMPORTANT: Force refetch all data
      await Promise.all([
        refetchFollowing(),
        refetchUsers(),
        StoryRefetch()
      ]);
      
      // Manually sync the follow status
      await syncFollowStatus();
      
    } catch (error: any) {
      // Revert on error - go back to original state
      dispatch(updateFollowStatus({ 
        userId: stringId, 
        isFollowing: isCurrentlyFollowing 
      }));
      showErrorToast(error?.data?.message || "Failed to follow/unfollow", "Something went wrong.");
    } finally {
      // Remove loading state
      setLoadingUsers(prev => ({ ...prev, [stringId]: false }));
    }
  };

  const handleUsernameClick = (user: any) => {
    if (!user?.username) return;
    router.push(`/Profile/${user.username}`);
  };

  // Get the latest follow status directly from the API response
  const getFollowStatus = (userId: string) => {
    // First check Redux state
    if (followedUsers[userId]) return true;
    
    // If not in Redux, check if this user is in FollowingData
    if (FollowingData?.follower) {
      const isFollowing = FollowingData.follower.some(
        (follow: any) => String(follow.follow_user_id) === userId
      );
      if (isFollowing) return true;
    }
    
    return false;
  };

  return (
    <div
      className="rounded-[10px] px-4 mx-2 sm:mx-0 py-4 bg-[var(--bg-primary)] dark:border dark:border-[color-mix(in_srgb,var(--border-color),white_07%)] transition-colors duration-200"
      style={{ 
        boxShadow: "0px 4px 20px 0px rgba(0, 0, 0, 0.08), 0px 0px 10px 0px rgba(255, 255, 255, 0.02)" 
      }}>
      <div className="flex justify-between items-center mb-2">
        <h2 className="text-[var(--text-primary)] font-gilroy_bold font-semibold text-lg">
          <TextTranslate text="Discover New People"/>
        </h2>
        {followingCount > 0 && (
          <span className="text-xs text-[var(--text-secondary)]">
            Following {followingCount}
          </span>
        )}
      </div>

      {isLoading ? (
        <div className="space-y-1">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="flex justify-between items-center py-2 animate-pulse">
              <div className="flex gap-3 items-center">
                <div className="h-11 w-11 bg-[var(--border-color)] rounded-full opacity-20" />
                <div className="space-y-2">
                  <div className="h-3 w-28 bg-[var(--border-color)] rounded opacity-20" />
                  <div className="h-2 w-20 bg-[var(--border-color)] rounded opacity-10" />
                </div>
              </div>
              <div className="h-8 w-[75px] rounded-xl bg-[var(--border-color)] opacity-20" />
            </div>
          ))}
        </div>
      ) : (
        <div className="flex flex-col">
          {UsersData?.tag_users?.slice(0, 8).map((user: any) => {
            const stringUserId = String(user.user_id);
            // Use the getFollowStatus function to get accurate status
            const isFollowing = getFollowStatus(stringUserId);
            const isLoading_ = loadingUsers[stringUserId];

            return (
              <div key={user.user_id} className="flex justify-between items-center py-2 group">
                <div className="flex gap-3 items-center">
                  <img
                    src={user.profile_pic || "/assets/ProfilePicRounded"}
                    alt="Profile"
                    className="h-11 w-11 object-cover rounded-full border border-[var(--border-color)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                  />

                  <div className="flex flex-col text-left">
                    <h2
                      className="text-[var(--text-primary)] font-medium text-sm font-gilroy_semibold cursor-pointer"
                      onClick={() => handleUsernameClick(user)}
                    >
                      {user.first_name} {user.last_name}
                    </h2>
                    <h3
                      className="text-[var(--text-secondary)] font-gilroy_md text-xs cursor-pointer"
                      onClick={() => handleUsernameClick(user)}
                    >
                      @{user.username}
                    </h3>
                  </div>
                </div>

                <button
                  disabled={isLoading_}
                  className={`rounded-xl font-gilroy_semibold text-[12px] h-fit w-[80px] py-1.5 transition-all duration-300 active:scale-95 ${
                    !isFollowing 
                      ? "bg-gradient-custom text-white hover:opacity-90 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%)] hover:bg-[color-mix(in_srgb,var(--text-primary),transparent_95%)]"
                  } ${isLoading_ ? "opacity-50 cursor-not-allowed" : ""}`}
                  onClick={() => handleFollow(user.user_id)}
                >
                  {isLoading_ ? (
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mx-auto"></div>
                  ) : isFollowing ? (
                    <TextTranslate text="Following"/>
                  ) : (
                    <TextTranslate text="Follow"/>
                  )}
                </button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default Discover;