"use client";
import SideDrawer from "@/components/common/SideDrawer";
import { useRef, useState, useEffect, useCallback } from "react";
import {
  IoCameraReverseOutline,
  IoCalendarOutline,
  IoSearchOutline,
  IoCloseOutline,
} from "react-icons/io5";
import { AiOutlineInfoCircle } from "react-icons/ai";
import Link from "next/link";
import { IoLocationOutline } from "react-icons/io5";
import { FaStar } from "react-icons/fa";
import { useTranslations } from "next-intl";
import EditProfileDrawer from "./EditProfileDrawer";
import { getStoredLocale } from "@/lib/getLocale";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { setUser } from "@/app/store/slices/authSlice";
import {
  getFollowLists,
  followUser,
  unfollowUser,
} from "@/lib/actions/followerFollowingActions";
import { useRouter } from "next/navigation";
import { useAppSelector, useAppDispatch } from "@/app/store/hooks";
import { toast } from "react-toastify";
import MobilePageHeader from "@/components/common/MobilePageHeader";
import {
  fetchUserProfile,
  updateProfileImage,
  populateFormData,
  extractUserData,
  filterFollowData,
  FollowData,
} from "@/lib/actions/profileActions";
import { getImageUrl } from "@/hooks/useImageUrl";
import { fetchProfileCountsAction } from "@/lib/actions/dashboardAction";
import {
  pieDataPremiumListings,
  pieDataOrders,
  pieDataFreeListings,
  orderCountSeller,
} from "../../../lib/helpers/dashboardConfig";
import { renderPieChart } from "@/components/Dashboard/CustomPieChart";
import ListingCard from "@/components/Dashboard/ListingCard";
import OrderSummaryCard from "@/components/Dashboard/OrderSummarycard";
import { ProfileActions } from "@/components/Dashboard/ProfileHeader/ProfileActions";
import { ProfileInfo } from "@/components/Dashboard/ProfileHeader/ProfileInfo";
import { ProfileImage } from "@/components/Dashboard/ProfileHeader/ProfileImage";
// for chart

// Custom Tooltip for PieChart
export default function Dashboard() {
  const t = useTranslations();
  const locale = getStoredLocale();
  const dispatch = useAppDispatch();
  const router = useRouter();
  const tOrder = useTranslations("orderStatus");
  const [activeDrawer, setActiveDrawer] = useState<
    null | "following" | "followers" | "editProfile"
  >(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [userProfile, setUserProfile] = useState<any>(null);
  const [isProfileLoaded, setIsProfileLoaded] = useState(false);
  const { user } = useAppSelector((state) => state?.auth);

  // Follow state with new backend structure
  const [followData, setFollowData] = useState<FollowData>({
    following: [],
    followers: [],
    totalFollowing: 0,
    totalFollowers: 0,
  });
  const [followSearch, setFollowSearch] = useState("");
  const [isFollowLoading, setIsFollowLoading] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  // Reusable function to pass to EditProfileDrawer
  const fetchUserProfileForDrawer = useCallback(async () => {
    if (!user?.token) return;

    setIsLoading(true);

    try {
      const result = await fetchUserProfile(user.token, locale);
      setUserProfile(result.userData);
      setIsProfileLoaded(true);
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      toast.error(error?.response?.data?.message || t("validation.error_msg"));
    } finally {
      setIsLoading(false);
    }
  }, [user?.token, dispatch, router, t]);

  // Fetch user profile data
  useEffect(() => {
    if (user?.token) {
      fetchUserProfileForDrawer();
    }
  }, [user?.token, fetchUserProfileForDrawer]);

  // Fetch follow data
  const fetchFollowData = useCallback(
    async (page = 1, append = false) => {
      if (!user?.token || (append && isLoadingMore)) return;

      const loadingState = append ? setIsLoadingMore : setIsFollowLoading;
      loadingState(true);

      try {
        const requestType =
          activeDrawer === "following"
            ? "following"
            : activeDrawer === "followers"
              ? "follower"
              : undefined;

        const result = await getFollowLists(
          user.token,
          followSearch ? undefined : 10, // only send limit if no search
          followSearch ? undefined : page, // only send page if no search
          followSearch || undefined,
          requestType,
        );

        const updateFollowData = (type: "followers" | "following") => {
          const data = result.data?.[type]?.data || [];
          const pagination = result.data?.[type]?.pagination;

          setFollowData((prev) => {
            const currentList = append ? prev[type] : [];
            const existingIds = new Set(
              currentList.map((item) =>
                type === "following"
                  ? item.followingId._id
                  : item.followerId._id,
              ),
            );

            const newItems = data.filter((item: any) => {
              const itemId =
                type === "following"
                  ? item.followingId._id
                  : item.followerId._id;
              return !existingIds.has(itemId);
            });

            const updatedList = [...currentList, ...newItems];

            if (requestType) {
              const isRequestType = type === requestType ? true : false;
              if (isRequestType) {
                setHasMore(pagination?.total > updatedList.length);
              }
            }

            return {
              ...prev,
              [type]: updatedList,
              [`total${type.charAt(0).toUpperCase() + type.slice(1)}`]:
                pagination?.total || 0,
            };
          });
        };

        if (requestType === "following") {
          updateFollowData("following");
        } else if (requestType === "follower") {
          updateFollowData("followers");
        } else {
          updateFollowData("following");
          updateFollowData("followers");
        }

        if (append) {
          setPage(page);
        }
      } catch (error: any) {
        if (error?.isAuthError && error?.status === 401) {
          if (checkAuthErrorGet(error.originalError, dispatch, router)) return;
        } else if (checkAuthErrorGet(error, dispatch, router)) return;
        toast.error(
          error?.response?.data?.message || t("validation.error_msg"),
        );
      } finally {
        loadingState(false);
        if (!append) {
          setIsSearching(false);
        }
      }
    },
    [
      user?.token,
      followSearch,
      activeDrawer,
      isLoadingMore,
      dispatch,
      router,
      t,
    ],
  );

  const closeDrawer = () => {
    setActiveDrawer(null);
    setFollowSearch("");
    setPage(1);
    setHasMore(true);
  };

  // Initial follow data fetch
  useEffect(() => {
    if (user?.token && activeDrawer) {
      fetchFollowData(1, false);
    }
  }, [user?.token, activeDrawer]);

  // Debounced search effect
  useEffect(() => {
    if (!user?.token) return;

    if (followSearch.trim()) {
      setIsSearching(true);
    }

    const timeoutId = setTimeout(() => {
      if (followSearch.trim()) {
        fetchFollowData(1, false);
      } else if (followSearch === "") {
        fetchFollowData(1, false);
      }
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [followSearch, user?.token]);

  // Update profile image when userProfile changes
  useEffect(() => {
    if (userProfile?.data?.data) {
      const userGetData = userProfile?.data?.data;
      const userData = extractUserData(userGetData);
      dispatch(
        setUser({
          first_name: userGetData?.first_name,
          last_name: userGetData?.last_name,
          username: userGetData?.username,
          email: userGetData?.email,
          profile: userData?.profile?.file_path,
        }),
      );
    }
  }, [userProfile, dispatch]);

  // Function to populate EditProfileDrawer form fields
  const populateDrawerForm = useCallback(() => {
    return populateFormData(userProfile);
  }, [userProfile]);

  const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) {
      return;
    }
    // Validate file type and size
    if (!file.type.startsWith("image/")) {
      toast.error(t("please_upload_valid_image"));
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error(t("image_file_should_be_less_than_5mb"));
      return;
    }

    try {
      setIsUploading(true);

      const result = await updateProfileImage(user?.token || "", file, locale);

      if (result.success) {
        toast.success(
          result.message || t("profile_image_updated_successfully"),
        );
        fetchUserProfileForDrawer();
      } else {
        toast.error(result.message || t("failed_to_update_image"));
      }
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      toast.error(
        error?.response?.data?.message ||
          t("validation.error_updating_profile_image"),
      );
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const [showTooltip, setShowTooltip] = useState(false);
  const userData = extractUserData(userProfile);

  // Helper function to check if a user is being followed
  const isUserFollowed = (userId: string) => {
    return followData.following.some((item) => item.followingId._id === userId);
  };
  const [counts, setCounts] = useState<any>(null);
  useEffect(() => {
    if (!user?.token) return;

    const fetchCounts = async () => {
      const response = await fetchProfileCountsAction(user.token);
      if (response.success) {
        setCounts(response.data);
      } else {
        // console.error(response.message);
      }
    };

    fetchCounts();
  }, [user?.token]);

  const handleFollowAction = async (
    userId: string,
    action: "follow" | "unfollow",
    userData?: any,
  ) => {
    if (!user?.token) return;

    // Store current state for potential rollback
    const previousFollowData = { ...followData };

    try {
      // Optimistically update the UI
      setFollowData((prev) => {
        const isCurrentlyFollowing = prev.following.some(
          (item) => item.followingId._id === userId,
        );

        // If already in the desired state, don't make any changes
        if (
          (action === "follow" && isCurrentlyFollowing) ||
          (action === "unfollow" && !isCurrentlyFollowing)
        ) {
          return prev;
        }

        if (action === "follow") {
          // When following, use the full user data if available
          const newFollower = userData
            ? {
                _id: `temp-${Date.now()}`,
                followingId: {
                  _id: userId,
                  first_name: userData.first_name,
                  last_name: userData.last_name,
                  username: userData.username,
                  profile: userData.profile,
                  isVerified: userData.isVerified,
                },
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
              }
            : {
                _id: `temp-${Date.now()}`,
                followingId: { _id: userId },
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
              };

          return {
            ...prev,
            following: [...prev.following, newFollower],
            totalFollowing: prev.totalFollowing + 1,
          };
        } else {
          // When unfollowing, just filter out the user
          return {
            ...prev,
            following: prev.following.filter(
              (item) => item.followingId._id !== userId,
            ),
            totalFollowing: Math.max(0, prev.totalFollowing - 1),
          };
        }
      });

      // Make the API call
      if (action === "follow") {
        await followUser(user.token, userId);
        toast.success(t("validation.user_followed_successfully"));
      } else {
        await unfollowUser(user.token, userId);
        toast.success(t("validation.user_unfollowed_successfully"));
      }
    } catch (error: any) {
      setFollowData(previousFollowData);

      if (error?.isAuthError && error?.status === 401) {
        if (checkAuthErrorGet(error.originalError, dispatch, router)) return;
      } else if (checkAuthErrorGet(error, dispatch, router)) return;

      toast.error(error?.response?.data?.message || t("validation.error_msg"));
    }
  };

  // Handle search in follow lists
  const handleFollowSearch = (searchTerm: string) => {
    setFollowSearch(searchTerm);
    setPage(1);
    setHasMore(true);
  };

  // Clear search function
  const clearSearch = () => {
    setFollowSearch("");
    setPage(1);
    setHasMore(true);
  };

  // Scroll handler for infinite scroll with debounce
  const handleScroll = useCallback(
    (e: React.UIEvent<HTMLDivElement>, type: "followers" | "following") => {
      if (isLoadingMore || !hasMore) return;

      const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
      const scrollThreshold = 100; // pixels from bottom

      if (scrollHeight - (scrollTop + clientHeight) < scrollThreshold) {
        // Prevent multiple rapid calls
        setHasMore(false);
        fetchFollowData(page + 1, true);
      }
    },
    [isLoadingMore, hasMore, page, fetchFollowData],
  );
  // Get filtered data for display
  const getFilteredData = useCallback(
    (type: "following" | "followers") => {
      const listData = followData[type];

      if (followSearch.trim()) {
        return listData;
      }

      return filterFollowData(listData, followSearch, type);
    },
    [followData, followSearch],
  );

  const handleBack = () => {
    window.history.back();
  };
  const statusColors: Record<string, string> = {
    pending: "#FACC15", // yellow
    processing: "#22C55E", // green
    shipped: "#3B82F6", // blue
    out_for_delivery: "#8B5CF6", // purple
    delivered: "#10B981", // emerald
    cancelled: "#EF4444", // red
  };

  const getPieData = (orders: Record<string, number>) =>
    Object.entries(orders)
      .filter(([_, value]) => value > 0)
      .map(([key, value]) => ({
        name: key.replace(/_/g, " "),
        value,
        color: statusColors[key] || "#9CA3AF",
      }));

  const getTotalOrders = (orders: Record<string, number>): number =>
    Object.values(orders).reduce((sum, count) => sum + count, 0);

  const buyerOrders = counts?.order?.orderCountBuyer || {};
  const sellerOrders = counts?.order?.orderCountSeller || {};
  const amount = counts?.order?.amount || { debit: 0, credit: 0 };

  const amountData = [
    { name: t("debit"), value: amount.debit, color: "#1577A8" },
    { name: t("credit"), value: amount.credit, color: "#38AFEA" },
  ];

  const pieDataBuyer = getPieData(buyerOrders);
  const pieDataSeller = getPieData(sellerOrders);

  const listing = counts?.listing as {
    created: number;
    remainingPosts: number;
    expired: number;
  };

  const listingData = [
    { name: t("created"), value: listing?.created, color: "#F59E0B" },
    { name: t("remaining"), value: listing?.remainingPosts, color: "#FDBA74" },
  ];

  const totalBuyer = getTotalOrders(buyerOrders);
  const totalSeller = getTotalOrders(sellerOrders);
  // Build dynamic statuses (only show keys that exist in data)
  const orderStatuses = Object.keys(statusColors).map((key) => ({
    key,
    label: tOrder(key),
    color: `${statusColors[key]}`,
  }));

  return (
    <>
      {/* Dashboard Content */}
      <MobilePageHeader title={t("dashboard.dashboard")} onBack={handleBack} />

      <div>
        <h1 className="text-lg font-bold text-gray-900 mb-6 dark:text-white max-md:hidden">
          {t("dashboard.dashboard")}
        </h1>

        <div className="bg-neutrals50 p-6 rounded-md dark:bg-darkbg">
          <div className="flex justify-between items-start max-sm:flex-col relative max-sm:justify-center max-[991px]:flex-wrap max-[991px]:gap-y-6 max-md:items-center max-sm:gap-y-0">
            <div className="flex items-center gap-4 max-sm:flex-col max-sm:justify-center max-sm:text-center">
              <ProfileImage
                user={user}
                profile={userData?.profile}
                isUploading={isUploading}
                fileInputRef={fileInputRef}
                handleImageChange={handleImageChange}
              />
              <ProfileInfo
                username={
                  userData?.first_name + " " + userData?.last_name ||
                  userData?.username
                }
                city={userData?.address?.city?.name}
                state={userData?.address?.state?.name}
                createdAt={userData?.createdAt}
                t={t}
              />
            </div>
            <ProfileActions
              followData={followData}
              setActiveDrawer={setActiveDrawer}
              t={t}
            />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4 pt-8 max-2xl:grid-cols-1">
          {/* Orders Card */}
          <div className="group-grid">
            <div className="grid grid-cols-2 gap-4 max-lg:grid-cols-2 max-sm:grid-cols-1">
              <OrderSummaryCard
                title={t("seller_order")}
                chartData={pieDataSeller}
                total={totalSeller}
                orderStatuses={orderStatuses}
                orderCounts={sellerOrders}
                viewAllLabel={t("dashboard.view_all")}
                subtitle={t("dashboard.based_list")}
                t={t}
              />

              <OrderSummaryCard
                title={t("buyer_order")}
                chartData={pieDataBuyer}
                total={totalBuyer}
                orderStatuses={orderStatuses}
                orderCounts={buyerOrders}
                viewAllLabel={t("dashboard.view_all")}
                subtitle={t("dashboard.based_list")}
                t={t}
              />
            </div>
          </div>
          <div className="bg-white shadow-Shadow1 rounded-lg p-6 dark:bg-darkbg">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-base font-medium text-neutrals800 dark:text-neutrals300">
                {t("dashboard.dashboard_listings")}
              </h3>
            </div>
            <div className="grid grid-cols-2 gap-3 max-lg:grid-cols-2 max-sm:grid-cols-1">
              {/* Free Listings */}
              <ListingCard
                title={t("dashboard.dashboard_listings")}
                subtitle={t("dashboard.based_list")}
                chartData={listingData}
                total={listingData[0].value + listingData[1].value}
                activeCount={listingData[0].value}
                expireCount={listingData[1].value}
                activeColor="#1577A8"
                expireColor="#38AFEA"
                linkLabel={t("dashboard.manage")}
                t={t}
              />

              <ListingCard
                title={t("amount")}
                subtitle={t("amount")}
                chartData={amountData}
                total={amountData[0].value + amountData[1].value}
                activeCount={amountData[0].value}
                expireCount={amountData[1].value}
                activeColor="#D97706"
                expireColor="#F59E0B"
                linkLabel={t("dashboard.manage")}
                t={t}
              />
            </div>
          </div>
        </div>
      </div>

      {/* 1. Following Drawer */}
      <SideDrawer
        isOpen={activeDrawer === "following"}
        title={t("dashboard_page.following")}
        onClose={closeDrawer}
      >
        <div className="flex flex-col h-full">
          <div className="flex-shrink-0">
            <div className="flex items-center p-1 pr-2 border border-neutrals200 rounded-md overflow-hidden w-full mb-7 dark:border-darkborder">
              <input
                type="text"
                placeholder={t("dashboard_page.search_following_users")}
                value={followSearch}
                onChange={(e) => setFollowSearch(e.target.value)}
                onKeyDown={(e) =>
                  e.key === "Enter" && handleFollowSearch(followSearch)
                }
                className="flex-grow px-4 py-3 pl-1 text-gray-500 placeholder-gray-400 focus:outline-none max-md:py-1.5 max-md:text-sm dark:bg-background dark:text-neutrals300"
              />
              {followSearch && (
                <button
                  onClick={clearSearch}
                  className="px-3 py-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                  type="button"
                >
                  <IoCloseOutline size={24} />
                </button>
              )}
              <button
                onClick={() => handleFollowSearch(followSearch)}
                disabled={isSearching}
                className="flex items-center gap-2 px-4 py-2.5 text-white bg-primary500 hover:bg-primary600 text-base rounded-lg max-md:p-0 max-md:bg-transparent  max-md:hover:bg-transparent max-md:text-neutrals400 max-md:text-sm max-md:font-normal dark:bg-primary400"
              >
                {isSearching ? (
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                ) : (
                  <IoSearchOutline size={24} />
                )}
                <span className="max-md:hidden">
                  {isSearching
                    ? t("dashboard_page.searching")
                    : t("dashboard_page.search")}
                </span>
              </button>
            </div>
            {followSearch && (
              <div className="mb-4 text-sm text-gray-600 dark:text-neutrals300">
                <span>
                  {t("dashboard_page.searching_for")} "{followSearch}"
                </span>
                {getFilteredData("following").length > 0 && (
                  <span className="ml-2">
                    • {getFilteredData("following").length}{" "}
                    {t("dashboard_page.results_of")} {followData.totalFollowing}{" "}
                    {t("dashboard_page.total")}
                  </span>
                )}
              </div>
            )}
          </div>

          <div
            className="flex-1 overflow-y-auto pt-2 "
            onScroll={(e) => handleScroll(e, "following")}
          >
            {isFollowLoading ? (
              <div className="flex justify-center items-center h-32">
                <div className="w-6 h-6 border-2 border-primary500 border-t-transparent rounded-full animate-spin"></div>
              </div>
            ) : getFilteredData("following").length > 0 ? (
              <ul className="space-y-4">
                {getFilteredData("following").map(
                  (item: any, index: number) => (
                    <li
                      key={index}
                      className="pb-4 border-b border-neutrals100 dark:border-darkborder"
                    >
                      {/* Your existing user item JSX */}
                      {item.followingId && (
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-3">
                            <div className="relative">
                              {item.followingId.profile?.file_path ? (
                                <img
                                  src={getImageUrl(
                                    item.followingId.profile.file_path,
                                  )}
                                  alt={item.followingId.username || "User"}
                                  className="w-12 h-12 rounded-full border-2 border-primary100 shadow-md cursor-pointer dark:border-darkborder"
                                  onError={(e) => {
                                    const target = e.target as HTMLImageElement;
                                    if (
                                      !target.src.endsWith(
                                        "/profile-avatar.png",
                                      )
                                    ) {
                                      target.onerror = null;
                                      target.src = "/profile-avatar.png";
                                    }
                                  }}
                                />
                              ) : (
                                <div className="w-12 h-12 rounded-full border-2 border-primary100 shadow-md cursor-pointer bg-primary400 dark:bg-primary400 flex items-center justify-center text-xl font-medium text-white">
                                  {(
                                    item.followingId.first_name?.[0] ||
                                    item.followingId.username?.[0] ||
                                    "U"
                                  ).toUpperCase()}
                                </div>
                              )}
                              {item.followingId.isVerified && (
                                <span className="absolute -top-1 -right-0">
                                  <img
                                    src="/checkmark.svg"
                                    alt="verified"
                                    className="w-4 h-4"
                                  />
                                </span>
                              )}
                            </div>
                            <div>
                              <h4 className="font-semibold text-neutrals900 dark:text-neutrals300">
                                {item.followingId.first_name &&
                                item.followingId.last_name
                                  ? `${item.followingId.first_name} ${item.followingId.last_name}`
                                  : item.followingId.username ||
                                    item.followingId.first_name ||
                                    "Unknown User"}
                              </h4>
                              <div className="flex items-center text-sm text-gray-600 dark:text-neutrals300">
                                <FaStar className="text-yellow-500 mr-1" />
                                {item.followingId.rating !== undefined &&
                                item.followingId.rating !== null
                                  ? `${item.followingId.rating}/5`
                                  : "No rating"}
                              </div>
                            </div>
                          </div>
                          <button
                            onClick={() =>
                              handleFollowAction(
                                item.followingId._id,
                                "unfollow",
                              )
                            }
                            className="px-4 py-2 text-sm font-medium text-primary500 hover:text-primary600 dark:text-primary400 dark:hover:text-primary300"
                          >
                            {t("dashboard_page.unfollow")}
                          </button>
                        </div>
                      )}
                    </li>
                  ),
                )}
                {isLoadingMore && (
                  <li className="flex justify-center py-4">
                    <div className="w-5 h-5 border-2 border-primary500 border-t-transparent rounded-full animate-spin"></div>
                  </li>
                )}
              </ul>
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-neutrals300">
                {t("dashboard_page.no_following_users_found")}
              </div>
            )}
          </div>
        </div>
      </SideDrawer>

      {/* Followers Drawer */}
      <SideDrawer
        isOpen={activeDrawer === "followers"}
        title={t("dashboard_page.followers")}
        onClose={closeDrawer}
      >
        <div className="flex flex-col h-full">
          <div className="flex-shrink-0">
            <div className="flex items-center p-1 pr-2 border border-neutrals200 rounded-md overflow-hidden w-full mb-7 dark:border-darkborder">
              <input
                type="text"
                placeholder={t("dashboard_page.search_followers")}
                value={followSearch}
                onChange={(e) => setFollowSearch(e.target.value)}
                onKeyDown={(e) =>
                  e.key === "Enter" && handleFollowSearch(followSearch)
                }
                className="flex-grow px-4 py-3 pl-1 text-gray-500 placeholder-gray-400 focus:outline-none max-md:py-1.5 max-md:text-sm dark:bg-background dark:text-neutrals300"
              />
              {followSearch && (
                <button
                  onClick={clearSearch}
                  className="px-3 py-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                  type="button"
                >
                  <IoCloseOutline size={24} />
                </button>
              )}
              <button
                onClick={() => handleFollowSearch(followSearch)}
                disabled={isSearching}
                className="flex items-center gap-2 px-4 py-2.5 text-white bg-primary500 hover:bg-primary600 text-base rounded-lg max-md:p-0 max-md:bg-transparent max-md:hover:bg-transparent max-md:text-neutrals400 max-md:text-sm max-md:font-normal dark:bg-primary400"
              >
                {isSearching ? (
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                ) : (
                  <IoSearchOutline size={24} />
                )}
                <span className="max-md:hidden">
                  {isSearching
                    ? t("dashboard_page.searching")
                    : t("dashboard_page.search")}
                </span>
              </button>
            </div>
            {followSearch && (
              <div className="mb-4 text-sm text-gray-600 dark:text-neutrals300">
                <span>
                  {t("dashboard_page.searching_for_followers")} "{followSearch}"
                </span>
                {getFilteredData("followers").length > 0 && (
                  <span className="ml-2">
                    • {getFilteredData("followers").length}{" "}
                    {t("dashboard_page.results_of")} {followData.totalFollowers}{" "}
                    {t("dashboard_page.total")}
                  </span>
                )}
              </div>
            )}
          </div>

          <div
            className="flex-1 overflow-y-auto pt-2"
            onScroll={(e) => handleScroll(e, "followers")}
          >
            {isFollowLoading ? (
              <div className="flex justify-center items-center h-32">
                <div className="w-6 h-6 border-2 border-primary500 border-t-transparent rounded-full animate-spin"></div>
              </div>
            ) : getFilteredData("followers").length > 0 ? (
              <ul className="space-y-4">
                {getFilteredData("followers").map(
                  (item: any, index: number) => (
                    <li
                      key={index}
                      className="pb-4 border-b border-neutrals100 dark:border-darkborder"
                    >
                      {item.followerId && (
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-3">
                            <div className="relative">
                              {item.followerId.profile?.file_path ? (
                                <img
                                  src={getImageUrl(
                                    item.followerId.profile.file_path,
                                  )}
                                  alt={item.followerId.username || "User"}
                                  className="w-12 h-12 rounded-full border-2 border-primary100 shadow-md cursor-pointer dark:border-darkborder"
                                  onError={(e) => {
                                    const target = e.target as HTMLImageElement;
                                    if (
                                      !target.src.endsWith(
                                        "/profile-avatar.png",
                                      )
                                    ) {
                                      target.onerror = null;
                                      target.src = "/profile-avatar.png";
                                    }
                                  }}
                                />
                              ) : (
                                <div className="w-12 h-12 rounded-full border-2 border-primary100 shadow-md cursor-pointer bg-primary400 dark:bg-primary400 flex items-center justify-center text-xl font-medium text-white">
                                  {(
                                    item.followerId.first_name?.[0] ||
                                    item.followerId.username?.[0] ||
                                    "U"
                                  ).toUpperCase()}
                                </div>
                              )}
                              {item.followerId.isVerified && (
                                <span className="absolute -top-1 -right-1">
                                  <img
                                    src="/checkmark.svg"
                                    alt="verified"
                                    className="w-4 h-4"
                                  />
                                </span>
                              )}
                            </div>
                            <div>
                              <h4 className="font-semibold text-neutrals900 dark:text-neutrals300">
                                {item.followerId.first_name &&
                                item.followerId.last_name
                                  ? `${item.followerId.first_name} ${item.followerId.last_name}`
                                  : item.followerId.username ||
                                    item.followerId.first_name ||
                                    t("unknown_user")}
                              </h4>
                              <div className="flex items-center text-sm text-gray-600 dark:text-neutrals300">
                                <FaStar className="text-yellow-500 mr-1" />
                                {item.followerId.rating !== undefined &&
                                item.followerId.rating !== null
                                  ? `${item.followerId.rating}/5`
                                  : t("no_rating")}
                              </div>
                            </div>
                          </div>
                          <button
                            onClick={() =>
                              handleFollowAction(
                                item.followerId._id,
                                isUserFollowed(item.followerId._id)
                                  ? "unfollow"
                                  : "follow",
                                item.followerId, // Pass the full user data
                              )
                            }
                            className="px-4 py-2 text-sm font-medium text-primary500 hover:text-primary600 dark:text-primary400 dark:hover:text-primary300"
                          >
                            {isUserFollowed(item.followerId._id)
                              ? t("dashboard_page.unfollow")
                              : t("dashboard_page.follow")}
                          </button>
                        </div>
                      )}
                    </li>
                  ),
                )}
                {isLoadingMore && (
                  <li className="flex justify-center py-4">
                    <div className="w-5 h-5 border-2 border-primary500 border-t-transparent rounded-full animate-spin"></div>
                  </li>
                )}
              </ul>
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-neutrals300">
                {followSearch
                  ? followData.followers.length > 0
                    ? `${t(
                        "dashboard_page.no_followers_found_for",
                      )} "${followSearch}"`
                    : t("dashboard_page.no_followers_found")
                  : t("dashboard_page.no_followers_found")}
              </div>
            )}
          </div>
        </div>
      </SideDrawer>

      {/* 3. Edit Profile Drawer */}

      <EditProfileDrawer
        isOpen={activeDrawer === "editProfile"}
        onClose={() => setActiveDrawer(null)}
        fetchUserProfile={fetchUserProfileForDrawer}
        populateForm={populateDrawerForm}
      />
    </>
  );
}
