"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Crown, Users } from "lucide-react";
import { useConnectionWords } from "@/lib/site-context";
import { Avatar } from "./Avatar";
import type { User } from "@/lib/types";

type Row = { user: User; followers: number; following: boolean };

/** Six colours, so the rows read the same way the trending ones do. */
const TINTS = [
  { tint: "rgba(230,57,70,.07)", accent: "#e63946" },
  { tint: "rgba(245,158,11,.07)", accent: "#f59e0b" },
  { tint: "rgba(16,185,129,.07)", accent: "#10b981" },
  { tint: "rgba(59,130,246,.07)", accent: "#3b82f6" },
  { tint: "rgba(139,92,246,.07)", accent: "#8b5cf6" },
  { tint: "rgba(236,72,153,.07)", accent: "#ec4899" },
];

/**
 * Who the most people follow.
 *
 * Built on the same wrapper and rows as Trending Topics above it, so the
 * two read as one column rather than two designs.
 */
export function TopFollowed() {
  const cw = useConnectionWords();
  const router = useRouter();
  const [rows, setRows] = useState<Row[]>([]);

  const load = useCallback(() => {
    fetch("/api/top-followed")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setRows(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  useEffect(load, [load]);

  if (rows.length === 0) return null;

  return (
    <div className="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-[#0c0c0c] p-4">
      <h3 className="flex items-center gap-1.5 font-semibold text-[15px] mb-3">
        <Crown size={15} className="text-amber-500" />{" "}
        {cw.mode === "friend" ? "Most friends" : "Top followed"}
      </h3>

      <div className="flex flex-col gap-1.5">
        {rows.map((row, i) => (
          <button
            key={row.user.id}
            onClick={() => router.push(`/${row.user.username}`)}
            className="tr-row"
            style={{
              ["--tint" as string]: TINTS[i % TINTS.length].tint,
              ["--accent" as string]: TINTS[i % TINTS.length].accent,
            }}
          >
            <span className="tr-rank">{i + 1}</span>

            <Avatar user={row.user} size={26} />

            <span className="tr-body">
              <span className="tr-tag">{row.user.name}</span>
              <span className="tr-count">@{row.user.username}</span>
            </span>

            <span className="tf-count">
              <Users size={11} />
              {row.followers.toLocaleString()}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}
