import { IoCloseOutline, IoSearchOutline } from "react-icons/io5";
import { FaStar } from "react-icons/fa";
import SideDrawer from "@/components/common/SideDrawer";
import React from "react";

interface User {
  _id: string;
  username?: string;
  first_name?: string;
  last_name?: string;
  profile?: { file_path?: string };
  rating?: number;
  isVerified?: boolean;
}

interface FollowerItem {
  followerId: User;
}

interface FollowersDrawerProps {
  isOpen: boolean;
  followData: { totalFollowers: number; followers: FollowerItem[] };
  followSearch: string;
  setFollowSearch: (value: string) => void;
  isSearching: boolean;
  isFollowLoading: boolean;
  isLoadingMore: boolean;
  t: (key: string) => string;
  onClose: () => void;
  handleFollowSearch: (query: string) => void;
  clearSearch: () => void;
  handleScroll: (e: React.UIEvent<HTMLDivElement>, type: "followers") => void;
  handleFollowAction: (
    userId: string,
    action: "follow" | "unfollow",
    user: User
  ) => void;
  isUserFollowed: (userId: string) => boolean;
  getFilteredData: (type: "followers") => FollowerItem[];
  getImageUrl: (filePath: string) => string;
}

export const FollowersDrawer = ({
  isOpen,
  followData,
  followSearch,
  setFollowSearch,
  isSearching,
  isFollowLoading,
  isLoadingMore,
  t,
  onClose,
  handleFollowSearch,
  clearSearch,
  handleScroll,
  handleFollowAction,
  isUserFollowed,
  getFilteredData,
  getImageUrl,
}: FollowersDrawerProps) => {
  return (
    <SideDrawer isOpen={isOpen} title={t("dashboard_page.followers")} onClose={onClose}>
      <div className="flex flex-col h-full">
        {/* Search Bar */}
        <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-neutrals400"
            />
            {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-neutrals400">
              <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>

        {/* Followers List */}
        <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, index) => (
                <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">
                        {/* Profile Image */}
                        <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>

                        {/* Name and Rating */}
                        <div>
                          <h4 className="font-semibold text-neutrals900 dark:text-neutrals400">
                            {item.followerId.first_name && item.followerId.last_name
                              ? `${item.followerId.first_name} ${item.followerId.last_name}`
                              : item.followerId.username ||
                                item.followerId.first_name ||
                                "Unknown User"}
                          </h4>
                          <div className="flex items-center text-sm text-gray-600 dark:text-neutrals400">
                            <FaStar className="text-yellow-500 mr-1" />
                            {item.followerId.rating != null
                              ? `${item.followerId.rating}/5`
                              : "No rating"}
                          </div>
                        </div>
                      </div>

                      {/* Follow / Unfollow Button */}
                      <button
                        onClick={() =>
                          handleFollowAction(
                            item.followerId._id,
                            isUserFollowed(item.followerId._id) ? "unfollow" : "follow",
                            item.followerId
                          )
                        }
                        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-neutrals400">
              {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>
  );
};
