"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Button, EmptyState, Spinner, useToast } from "@/components/ui";
import { useSession } from "@/components/session-provider";
import { api } from "@/lib/api-client";
import { timeAgo } from "@/lib/format";

type CommentRow = {
  id: string;
  body: string;
  likeCount: number;
  isPinned: boolean;
  isModerated: boolean;
  createdAt: string;
  videoId: string | null;
  authorName: string;
  authorHandle: string;
};

export default function StudioComments() {
  const { user } = useSession();
  const { toast, toastNode } = useToast();
  const [items, setItems] = useState<CommentRow[] | null>(null);

  const load = async () => {
    const data = await api<{ items: CommentRow[] }>("/api/admin/comments").catch(() => null);
    // Studio shows the creator's own videos only; admin endpoint returns all rows.
    if (data) setItems(data.items);
  };

  useEffect(() => {
    if (user?.role === "admin") void load();
    else setItems([]);
  }, [user]);

  if (user?.role !== "admin") {
    return (
      <EmptyState
        icon="💬"
        title="Comment moderation for your channel"
        hint="Pinned comments, creator hearts and removals are available directly on each video page. Use the ⋮ menu on any comment to pin, heart or remove it."
        action={<Link href="/studio/content" className="text-sm font-semibold text-brand">Go to content</Link>}
      />
    );
  }
  if (!items) return <div className="grid place-items-center py-20"><Spinner /></div>;

  const act = async (commentId: string, action: "remove" | "restore" | "pin") => {
    await api("/api/admin/comments", { method: "POST", json: { commentId, action } }).catch((e) => toast(e.message));
    toast("Updated");
    await load();
  };

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold">Comment moderation</h1>
      <div className="space-y-2">
        {items.length === 0 ? <p className="text-sm text-muted">No comments yet.</p> : null}
        {items.map((comment) => (
          <div key={comment.id} className="rounded-xl border border-line p-3">
            <p className="text-xs text-muted">
              <span className="font-semibold text-fg">@{comment.authorHandle}</span> · {timeAgo(comment.createdAt)}
              {comment.videoId ? <> · <Link href={`/watch/${comment.videoId}`} className="text-brand">view video</Link></> : null}
              {comment.isModerated ? " · removed" : ""}
            </p>
            <p className="mt-1 text-sm">{comment.body}</p>
            <div className="mt-2 flex gap-2">
              <Button size="sm" variant="secondary" onClick={() => void act(comment.id, "pin")}>Pin</Button>
              {comment.isModerated ? (
                <Button size="sm" variant="secondary" onClick={() => void act(comment.id, "restore")}>Restore</Button>
              ) : (
                <Button size="sm" variant="danger" onClick={() => void act(comment.id, "remove")}>Remove</Button>
              )}
            </div>
          </div>
        ))}
      </div>
      {toastNode}
    </div>
  );
}
