"use client";
/** Moderation log with undo (SOC-063) and the author blocklist. */
import Link from "next/link";
import { useState } from "react";
import { ArrowLeft, ShieldCheck, Undo2 } from "lucide-react";
import { Badge, Button, Card, Empty, PageHeader, Segmented, Spinner, Tabs, api, useUI } from "@/components/ui";
import { fmtDate, useApi } from "@/components/hooks";
import { CHANNEL_LABEL } from "@/components/social";

export default function ModerationPage() {
  const [tab, setTab] = useState<"log" | "blocked">("log");
  const [actor, setActor] = useState("");
  const log = useApi<{ data: any[] }>(`/moderation/log${actor ? `?filter[actor]=${actor}` : ""}`, [actor]);
  const blocked = useApi<{ data: any[] }>(tab === "blocked" ? "/social/blocklist" : null, [tab]);
  const team = useApi<{ timezone: string; perms: Record<string, string> }>("/team");
  const { push } = useUI();
  const canModerate = team.data?.perms.social_moderate === "C";
  const undo = async (id: string) => { try { await api(`/moderation/${id}/undo`, { body: {} }); push("ok", "Comment unhidden"); log.reload(); } catch (e) { push("error", (e as Error).message); } };
  const unblock = async (id: string) => { try { await api(`/social/blocklist/${id}`, { method: "DELETE" }); push("ok", "Author unblocked"); blocked.reload(); } catch (e) { push("error", (e as Error).message); } };
  return (
    <div>
      <Link href="/inbox" className="mb-2 inline-flex items-center gap-1 text-[12.5px] text-ink-3 hover:text-brand"><ArrowLeft className="h-3.5 w-3.5" />Inbox</Link>
      <PageHeader title="Moderation" subtitle="Every hide, delete and spam action — by people, rules or AI — with the reason. Hides can be undone." />
      <div className="mb-3 flex flex-wrap items-center gap-3">
        <Tabs value={tab} onChange={setTab} tabs={[{ value: "log", label: "Moderation log" }, { value: "blocked", label: "Blocked authors" }]} />
        {tab === "log" && <Segmented size="sm" value={actor} onChange={setActor} options={[{ value: "", label: "Everyone" }, { value: "rule", label: "Rules" }, { value: "user", label: "People" }, { value: "ai", label: "AI" }]} />}
      </div>
      {tab === "log" ? (
        !log.data ? <Spinner /> : !log.data.data.length ? <Empty icon={<ShieldCheck className="h-5 w-5" />} title="Nothing moderated yet">Hidden and deleted comments will be listed here.</Empty> : (
          <Card bodyClass="p-0">
            <ul className="divide-y divide-line/60">
              {log.data.data.map((e) => (
                <li key={e.id} className="flex flex-wrap items-start gap-3 px-4 py-3 text-[13px]">
                  <Badge tone={e.action === "delete" ? "red" : e.action === "unhide" ? "green" : "amber"}>{e.action.replace("_", " ")}</Badge>
                  <div className="min-w-0 flex-1">
                    <p className="line-clamp-2">“{e.comment.body}”</p>
                    <p className="mt-0.5 text-[11.5px] text-ink-3">{e.comment.author ?? "Someone"} on {CHANNEL_LABEL[e.comment.channel] ?? e.comment.channel} · by {e.actorName ?? e.actorType} ({e.actorType}){e.reason ? ` · ${e.reason}` : ""} · {fmtDate(e.createdAt, team.data?.timezone)}{e.undoneAt ? " · undone" : ""}</p>
                  </div>
                  <div className="flex gap-2">
                    <Link href={`/inbox?c=${e.comment.conversationId}`} className="text-[12px] text-brand">Open</Link>
                    {canModerate && (e.action === "hide" || e.action === "mark_spam") && !e.undoneAt && e.comment.isHidden && <Button size="sm" icon={<Undo2 className="h-3.5 w-3.5" />} onClick={() => undo(e.id)}>Undo</Button>}
                  </div>
                </li>
              ))}
            </ul>
          </Card>
        )
      ) : !blocked.data ? <Spinner /> : !blocked.data.data.length ? <Empty icon={<ShieldCheck className="h-5 w-5" />} title="No blocked authors">Block an author from a comment's menu; their future comments are hidden automatically.</Empty> : (
        <Card bodyClass="p-0">
          <ul className="divide-y divide-line/60">{blocked.data.data.map((b) => <li key={b.id} className="flex items-center gap-3 px-4 py-2.5 text-[13px]"><span className="flex-1"><b>{b.authorName ?? b.authorExternalId}</b> <span className="text-ink-3">· {b.platform} · {b.reason}</span></span>{canModerate && <Button size="sm" onClick={() => unblock(b.id)}>Unblock</Button>}</li>)}</ul>
        </Card>
      )}
    </div>
  );
}
