"use client";

import React, { useState } from "react";
import Image from "next/image";
import ReactPaginate from "react-paginate";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useAppSelector } from "@/redux/hooks";
import {
  useGetFollowersQuery,
  useGetFollowingQuery,
  useFollowUserMutation,
} from "@/api/auth.api";
import { IFollowUser, IFollowerItem, IFollowingItem } from "@/api/types/auth";

const FALLBACK_AVATAR = "/assets/images/avatar-dummy.png";
const PER_PAGE = 20;

type Tab = "followers" | "following";

interface UserCardProps {
  user: IFollowUser;
  tab: Tab;
}

const UserCard: React.FC<UserCardProps> = ({ user, tab }) => {
  const [followUser, { isLoading }] = useFollowUserMutation();
  const [optimisticUnfollowed, setOptimisticUnfollowed] = useState(false);

  const handleToggle = async () => {
    setOptimisticUnfollowed(true);
    try {
      await followUser(user.id).unwrap();
    } catch {
      setOptimisticUnfollowed(false);
    }
  };

  const showUnfollow = tab === "following" && !optimisticUnfollowed;
  const buttonLabel = isLoading ? "…" : showUnfollow ? "Unfollow" : "Follow";
  const buttonClass = showUnfollow
    ? "w-28 h-8 rounded-[100px] border border-blue-light bg-blue-light text-white text-base font-bold leading-5 flex items-center justify-center hover:bg-blue-light-hover transition-all disabled:opacity-60 cursor-pointer"
    : "w-28 h-8 rounded-[100px] border border-blue-light text-blue-light text-base font-bold leading-5 flex items-center justify-center hover:bg-blue-icy transition-all disabled:opacity-60 cursor-pointer";

  return (
    <div className="w-72 p-4  bg-white rounded-2xl outline outline-neutral-200 -outline-offset-1 inline-flex flex-col justify-center items-center gap-3.5 hover:shadow-[0_0_24px_0_rgba(0,0,0,0.08)] transition-shadow">
      <div className="w-56 flex flex-col justify-center items-center gap-2.5">
        <div className="w-56 flex flex-col justify-center items-center gap-2">
          <div className="relative size-20 rounded-[50px] overflow-hidden bg-zinc-300 shrink-0">
            <Image
              src={user.profileImage?.filePath ?? FALLBACK_AVATAR}
              alt={user.name}
              fill
              className="object-cover"
            />
          </div>
          <div className="self-stretch flex flex-col justify-center items-center gap-1">
            <div className="text-black text-lg font-medium leading-5 text-center">
              {user.name}
            </div>
            {user.userProfile.rank && (
              <div className="self-stretch text-center text-gray-500 text-base font-normal leading-5">
                {user.userProfile.rank.name}
              </div>
            )}
          </div>
        </div>
        <button
          onClick={handleToggle}
          disabled={isLoading}
          className={buttonClass}
        >
          {buttonLabel}
        </button>
      </div>
    </div>
  );
};

const SkeletonCard = () => (
  <div className="w-72 p-2.5 bg-white rounded-2xl outline outline-neutral-200 -outline-offset-1 inline-flex flex-col justify-center items-center gap-3.5 animate-pulse">
    <div className="w-56 flex flex-col justify-center items-center gap-2.5">
      <div className="w-56 flex flex-col justify-center items-center gap-2">
        <div className="size-20 rounded-[50px] bg-gray-200" />
        <div className="self-stretch flex flex-col justify-center items-center gap-1">
          <div className="h-5 w-28 bg-gray-200 rounded" />
          <div className="h-5 w-20 bg-gray-200 rounded" />
        </div>
      </div>
      <div className="w-28 h-8 bg-gray-200 rounded-[100px]" />
    </div>
  </div>
);

const FollowListSection = () => {
  const [activeTab, setActiveTab] = useState<Tab>("followers");
  const [page, setPage] = useState(1);
  const { user } = useAppSelector((state) => state.auth);
  const userId = user?.id ?? "";

  const {
    data: followersData,
    isLoading: loadingFollowers,
    isFetching: fetchingFollowers,
  } = useGetFollowersQuery(
    { id: userId, page, perPage: PER_PAGE },
    { skip: !userId || activeTab !== "followers" },
  );

  const {
    data: followingData,
    isLoading: loadingFollowing,
    isFetching: fetchingFollowing,
  } = useGetFollowingQuery(
    { id: userId, page, perPage: PER_PAGE },
    { skip: !userId || activeTab !== "following" },
  );

  const isLoading =
    activeTab === "followers" ? loadingFollowers : loadingFollowing;
  const isFetching =
    activeTab === "followers" ? fetchingFollowers : fetchingFollowing;

  const items =
    activeTab === "followers"
      ? (followersData?.data ?? [])
      : (followingData?.data ?? []);

  const totalPages =
    activeTab === "followers"
      ? (followersData?.totalPages ?? 1)
      : (followingData?.totalPages ?? 1);

  const totalRecords =
    activeTab === "followers"
      ? (followersData?.totalRecords ?? 0)
      : (followingData?.totalRecords ?? 0);

  const handleTabChange = (tab: Tab) => {
    setActiveTab(tab);
    setPage(1);
  };

  const tabs: { id: Tab; label: string }[] = [
    { id: "followers", label: "Followers" },
    { id: "following", label: "Following" },
  ];

  return (
    <div className="flex flex-col w-full gap-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-black font-bold text-[20px] leading-[1.2] tracking-[-0.2px]">
          Follow List
        </h2>
        {totalRecords > 0 && (
          <span className="text-gray-515 text-[13px] font-medium">
            {totalRecords}{" "}
            {activeTab === "followers" ? "follower" : "following"}
            {totalRecords !== 1 ? "s" : ""}
          </span>
        )}
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 border-b border-gray-215">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => handleTabChange(tab.id)}
            className={`px-5 py-2.5 text-[15px] font-semibold leading-[1.2] tracking-[-0.15px] border-b-2 transition-colors cursor-pointer -mb-px ${
              activeTab === tab.id
                ? "border-blue-light text-blue-light"
                : "border-transparent text-gray-590 hover:text-gray-900"
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Grid */}
      {isLoading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {Array.from({ length: 6 }).map((_, i) => (
            <SkeletonCard key={i} />
          ))}
        </div>
      ) : items.length === 0 ? (
        <div className="flex items-center justify-center py-16">
          <span className="text-gray-400 text-[15px]">
            No {activeTab === "followers" ? "followers" : "following"} yet.
          </span>
        </div>
      ) : (
        <div
          className={`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 transition-opacity ${
            isFetching ? "opacity-60" : "opacity-100"
          }`}
        >
          {items.map((item) => {
            const person =
              activeTab === "followers"
                ? (item as IFollowerItem).follower
                : (item as IFollowingItem).following;
            return <UserCard key={item.id} user={person} tab={activeTab} />;
          })}
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <ReactPaginate
          pageCount={totalPages}
          pageRangeDisplayed={3}
          marginPagesDisplayed={1}
          forcePage={page - 1}
          onPageChange={({ selected }) => setPage(selected + 1)}
          previousLabel={<ChevronLeft size={15} strokeWidth={2} />}
          nextLabel={<ChevronRight size={15} strokeWidth={2} />}
          breakLabel="…"
          containerClassName="flex items-center justify-center gap-1.5 mt-2"
          pageClassName="flex"
          pageLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-285 text-gray-590 text-[14px] font-semibold hover:bg-gray-150 transition-colors cursor-pointer"
          activeClassName="[&>a]:bg-blue-light [&>a]:text-white [&>a]:border-blue-light"
          previousClassName="flex"
          previousLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-285 text-gray-590 hover:bg-gray-150 transition-colors cursor-pointer"
          nextClassName="flex"
          nextLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-285 text-gray-590 hover:bg-gray-150 transition-colors cursor-pointer"
          breakClassName="flex"
          breakLinkClassName="w-8 h-8 flex items-center justify-center text-gray-515 text-[14px]"
          disabledClassName="opacity-40 pointer-events-none"
        />
      )}
    </div>
  );
};

export default FollowListSection;
