"use client";
import React, { useEffect, useState, useMemo } from "react";
import Cookies from "js-cookie";
import toast from "react-hot-toast";
import useApiPost from "../../hooks/postData";
import { useRouter } from "next/navigation";
import Image from "next/image";
import NoPostGif from "../../../../public/assets/NoPost.png";
import { User } from "../../types/SearchUserType";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import { setUserId } from "@/app/store/Slice/SetUserIdForChatOpen";
import { ClipLoader } from "react-spinners";
import TextTranslate from "@/app/utils/TextTranslate";
import { useTranslateText } from "@/app/hooks/useTranslate";
import { X } from "lucide-react";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";


function Following({ onClose }: { onClose: () => void }) {
  const userId = useAppSelector((state) => state.userid.userId);
  const { data, loading, error, postData } = useApiPost();
  const router = useRouter();
  const translate = useTranslateText();

  const [followedUsers, setFollowedUsers] = useState<{
    [key: string]: boolean;
  }>({});
  const [followingList, setFollowingList] = useState<User[]>([]);

  // to get following data of second user
  useEffect(() => {
    const handleFollowing = async () => {
      if (!userId) return;
      try {
        const response = await postData("/second_user_following", {
          to_user_id: userId,
        });
        console.log("Following API Response:", response);
        setFollowingList(response?.follower || []);
      } catch (error: any) {
        showErrorToast(error?.message || "Failed to load following list");
      }
    };
    handleFollowing();
  }, [userId]);

  // to open user profile using username
  const dispatch = useAppDispatch();
  const handleUsernameClick = async (followUserId: string, username?: string) => {
    // If username is available, use it directly
    if (username) {
      dispatch(setUserId(followUserId));
      router.push(`/Profile/${username}`);
      onClose();
      return;
    }
    
    // If username is not available, fetch user profile to get username
    try {
      const response = await postData("/second_user_profile", {
        to_user_id: followUserId,
      });
      const fetchedUsername = response?.user_data?.username;
      if (fetchedUsername) {
        dispatch(setUserId(followUserId));
        router.push(`/Profile/${fetchedUsername}`);
        onClose();
      } else {
        showErrorToast("Unable to open profile");
      }
    } catch (error) {
      console.error("Error fetching user profile:", error);
      showErrorToast("Unable to open profile");
    }
  };

  // To search user based on username
  const [searchTerm, setSearchTerm] = useState("");
  const users: User[] = Array.isArray(followingList) ? followingList : [];
  const filteredUsers = useMemo(() => {
    return users.filter(
      (user) =>
        (user?.first_name + " " + user?.last_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        user?.username?.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [users, searchTerm]);

  const { postData: followUserPostData } = useApiPost();

  const handleFollow = async (followUserId: string) => {
    const user = followingList.find((u) => u.follow_user_id === followUserId);
    const isCurrentlyFollowing = user?.is_follow === "1";

    // Optimistic UI update
    setFollowingList((prev) =>
      prev.map((u) =>
        u.follow_user_id === followUserId
          ? { ...u, is_follow: isCurrentlyFollowing ? "0" : "1" }
          : u
      )
    );

    try {
      await followUserPostData("/follow", { to_user: followUserId });
      // Dispatch event to update other components
      window.dispatchEvent(
        new CustomEvent("profileUpdated", {
          detail: { type: "follow" },
        })
      );
    } catch (error) {
      toast.error("Failed to update follow status.");
      // Revert on failure
      setFollowingList((prev) =>
        prev.map((u) =>
          u.follow_user_id === followUserId
            ? { ...u, is_follow: isCurrentlyFollowing ? "1" : "0" }
            : u
        )
      );
    }
  };

  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-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]">
          <button
            onClick={onClose}
            className="absolute left-6 text-[var(--text-primary)]/80 hover:text-[var(--text-primary)] transition-colors"
          >
            <X size={24} />
          </button>
          <h2 className="text-[var(--text-primary)] font-gilroy_semibold font-bold text-[17px]">
            <TextTranslate text="Following" />
          </h2>
        </div>

        {/* Search */}
        <div className="flex items-center px-4 sm:px-6 py-2 mb-2 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]">
          <img
            src="/assets/follower_search.png"
            className="w-4 h-4 mr-3 opacity-50 img-theme"
            alt="search"
          />
          <input
            type="text"
            placeholder={translate("Search Here")}
            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 ? (
            <div className="flex justify-center py-10 text-sm text-[var(--text-secondary)]">
              <ClipLoader color="#452B7A" size={25} />
            </div>
          ) : followingList?.length > 0 ? (
            searchTerm ? (
              // Search results
              filteredUsers.map((user) => (
                <div
                  key={user.follow_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%)] transition-colors"
                >
                  <div className="flex items-center gap-3 flex-1">
                    <img
                      src={user.profile_pic || "/assets/default_user.png"}
                      alt={user.first_name}
                      className="w-12 h-12 rounded-full object-cover border border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                    />
                    <div className="flex flex-col">
                      <button
                        onClick={() => handleUsernameClick(user?.follow_user_id, user?.username)}
                        className="text-left"
                      >
                        <h3 className="text-[var(--text-primary)] font-gilroy_semibold font-bold text-[15px]">
                          {user.first_name} {user.last_name}
                        </h3>
                        <p className="text-[var(--text-secondary)] text-[13px]">
                          @{user.username || user.first_name?.toLowerCase()}
                        </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 text-white bg-gradient-custom"
                    onClick={() => handleFollow(user?.follow_user_id)}
                  >
                    <TextTranslate text="Follow" />
                  </button>
                </div>
              ))
            ) : (
              // Full following list
              followingList.map((follower) => (
                <div
                  key={follower.follow_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%)] transition-colors"
                >
                  <div className="flex items-center gap-3 flex-1">
                    <img
                      src={follower?.profile_pic || "/assets/default_user.png"}
                      alt="Profile Image"
                      className="w-12 h-12 rounded-full object-cover border border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                    />
                    <div className="flex flex-col">
                      <button
                        onClick={() => handleUsernameClick(follower?.follow_user_id, follower?.username)}
                        className="text-left"
                      >
                        <h2 className="text-[var(--text-primary)] font-gilroy_semibold font-bold text-[15px]">
                          {follower?.first_name} {follower?.last_name}
                        </h2>
                        <p className="text-[var(--text-secondary)] text-[13px]">
                          @{follower?.username || follower?.first_name?.toLowerCase()}
                        </p>
                      </button>
                    </div>
                  </div>

                  {follower.is_me === "0" && (
                    <button
                      className={`rounded-xl font-gilroy_semibold text-[12px] h-fit w-[80px] py-1.5 transition-all duration-300 active:scale-95 ${
                        follower.is_follow === "1"
                          ? "text-[#341F60] dark:text-[var(--text-primary)] bg-transparent border border-[#341F60] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]"
                          : "text-white bg-gradient-custom"
                      }`}
                      onClick={() => handleFollow(follower.follow_user_id)}
                    >
                      {follower.is_follow === "1" ? (
                        <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 following"
                className="w-16 h-16 opacity-20 img-theme"
              />
              <span className="mt-4 text-[var(--text-secondary)] text-[14px]">
                <TextTranslate text="Not following anyone yet" />
              </span>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 sm:px-6 mt-4 -mb-3">
          <button
            onClick={onClose}
            className="w-full py-2.5 bg-[#341F60] text-white rounded-xl font-bold hover:opacity-90 transition-opacity"
          >
            <TextTranslate text="Done" />
          </button>
        </div>
      </div>
    </div>
  );
}

export default Following;