"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { UserPlus, Check, X } from "lucide-react";
import { Avatar } from "./Avatar";
import type { User } from "@/lib/types";
import { useConnectionWords } from "@/lib/site-context";

/**
 * People waiting on an answer from you.
 *
 * The same list under both social models, because it is the same rows:
 * someone pointing at you that you don't point back at. What differs is
 * only what it is called and what accepting means -- a follow back, or a
 * friendship. See lib/connection-mode.
 */
export function FollowRequests() {
  const c = useConnectionWords();
  const [people, setPeople] = useState<(User & { mutualCount?: number })[]>([]);
  const [busy, setBusy] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/follow-requests")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setPeople(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  async function answer(id: string, action: "accept" | "decline") {
    setBusy(id);
    await fetch("/api/follow-requests", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userId: id, action }),
    }).catch(() => {});
    setBusy(null);
    setPeople((list) => list.filter((p) => p.id !== id));
  }

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

  return (
    <section className="fr-card">
      <h3 className="fr-head">
        <UserPlus size={16} /> {c.requests}
        <span className="fr-count">{people.length}</span>
      </h3>

      {people.slice(0, 4).map((p) => (
        <div key={p.id} className="fr-row">
          <Link href={`/${p.username}`} className="shrink-0">
            <Avatar user={p} size={44} />
          </Link>

          <div className="fr-who">
            <Link href={`/${p.username}`}>
              <b>{p.name}</b>
            </Link>
            <em>
              {p.mutualCount
                ? `${p.mutualCount} mutual${p.mutualCount === 1 ? "" : "s"}`
                : `@${p.username}`}
            </em>
          </div>

          {/* Beside the name, not beneath it. Two labelled buttons on their
              own row made each request three lines tall, so four requests
              filled the rail. The rail is ~276px inside its padding, and
              the words alone would leave about 70px for a name -- so the
              answer is the icon with the words on hover, not smaller text
              nobody can read. */}
          <div className="fr-acts">
            <button
              onClick={() => answer(p.id, "accept")}
              disabled={busy === p.id}
              className="fr-yes"
              title={c.accept}
              aria-label={`${c.accept} — ${p.name}`}
            >
              <Check size={16} strokeWidth={2.8} />
            </button>
            <button
              onClick={() => answer(p.id, "decline")}
              disabled={busy === p.id}
              className="fr-no"
              title="Decline"
              aria-label={`Decline — ${p.name}`}
            >
              <X size={16} strokeWidth={2.8} />
            </button>
          </div>
        </div>
      ))}
    </section>
  );
}
