import { useState } from "react";
import { useAuth } from "@/context/auth-context";
import { useQuery } from "@tanstack/react-query";
import { client } from "@/client";
import { Users, UserPlus } from "lucide-react";
import { Link } from "react-router";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { workspaceColor, workspaceInitial } from "@/components/shell/shared";

export default function MeFollowingPage() {
  const { me } = useAuth();
  const username = me?.username ?? "";
  const [tab, setTab] = useState<"followers" | "following">("followers");

  const { data: followers = [], isLoading: loadingFollowers } = useQuery({
    queryKey: ["me", "followers", username],
    queryFn: async () => {
      const res = await client.usersFollowers(username);
      return res.data;
    },
    enabled: Boolean(username),
    retry: false,
  });

  const { data: following = [], isLoading: loadingFollowing } = useQuery({
    queryKey: ["me", "following", username],
    queryFn: async () => {
      const res = await client.usersFollowing(username);
      return res.data;
    },
    enabled: Boolean(username),
    retry: false,
  });

  const { data: counts } = useQuery({
    queryKey: ["me", "relation-counts", username],
    queryFn: async () => {
      const res = await client.usersRelationCounts(username);
      return res.data;
    },
    enabled: Boolean(username),
    retry: false,
  });

  const tabs = [
    { key: "followers" as const, label: "Followers", count: counts?.followers ?? followers.length },
    { key: "following" as const, label: "Following", count: counts?.following ?? following.length },
  ];

  const currentList = tab === "followers" ? followers : following;
  const isLoading = tab === "followers" ? loadingFollowers : loadingFollowing;

  return (
    <div className="mx-auto max-w-2xl px-8 py-10">
      <h1 className="text-xl font-heading font-bold text-foreground">Following</h1>

      {/* Tab switch */}
      <nav className="mt-6 grid grid-cols-2 gap-1 rounded-xl bg-muted/70 p-1">
        {tabs.map((t) => (
          <button
            className={cn(
              "flex h-8 items-center justify-center gap-2 rounded-md text-sm font-semibold text-muted-foreground transition-colors hover:text-foreground",
              tab === t.key && "bg-card text-foreground shadow-sm ring-1 ring-border",
            )}
            key={t.key}
            onClick={() => setTab(t.key)}
          >
            {t.label}
            <span className="font-mono text-xs">{t.count}</span>
          </button>
        ))}
      </nav>

      {/* User list */}
      <div className="mt-6 space-y-1">
        {isLoading ? (
          Array.from({ length: 3 }).map((_, i) => (
            <div className="h-10 animate-pulse rounded-lg bg-muted" key={i} />
          ))
        ) : currentList.length > 0 ? (
          currentList.map((user) => (
            <div className="flex items-center gap-3 rounded-lg px-3 py-3 hover:bg-accent/50 transition-colors" key={user.username}>
              <Link className="flex items-center gap-3 min-w-0 flex-1" to={`/${user.username}`}>
                <span className={`grid size-8 place-items-center rounded-lg bg-gradient-to-br text-xs font-bold text-white ${workspaceColor(user.username)}`}>
                  {user.avatar_url ? <img alt="" className="size-full object-cover" src={user.avatar_url} /> : workspaceInitial(user.username)}
                </span>
                <div className="min-w-0">
                  <p className="font-heading font-medium text-foreground">{user.display_name ?? user.username}</p>
                  <p className="font-mono text-xs text-muted-foreground">@{user.username}</p>
                </div>
              </Link>
              {user.is_following ? (
                <span className="font-mono text-xs text-muted-foreground">Following</span>
              ) : (
                <Button className="rounded-lg text-xs h-7" size="sm" variant="outline">
                  <UserPlus className="size-3" />
                  Follow
                </Button>
              )}
            </div>
          ))
        ) : (
          <div className="py-10 text-center">
            <Users className="mx-auto size-5 text-muted-foreground/30" />
            <p className="mt-3 text-sm text-muted-foreground">
              {tab === "followers" ? "No followers yet" : "Not following anyone yet"}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}