import Link from "next/link";
import { apiFetch } from "@/lib/api";
import { WebhooksClient } from "./webhooks-client";

interface Board {
  id: string;
  name: string;
  publicKey: string;
}

interface Webhook {
  id: string;
  boardId: string;
  url: string;
  events: string[];
  enabled: boolean;
  createdAt: string;
}

async function load(id: string): Promise<{ board: Board | null; hooks: Webhook[] }> {
  const [bRes, wRes] = await Promise.all([
    apiFetch(`/v1/boards/${id}`),
    apiFetch(`/v1/webhooks/board/${id}`),
  ]);
  if (!bRes.ok) return { board: null, hooks: [] };
  return { board: await bRes.json(), hooks: wRes.ok ? await wRes.json() : [] };
}

export default async function WebhooksPage({ params }: { params: { id: string } }) {
  const { board, hooks } = await load(params.id);
  if (!board) return <div className="text-white/60">Board not found.</div>;
  return (
    <div className="space-y-6">
      <div>
        <Link href={`/dashboard/boards/${board.id}`} className="text-xs text-white/40 hover:text-white">← board</Link>
        <h1 className="text-3xl font-bold mb-1 mt-1">Webhooks</h1>
        <p className="text-sm text-white/60">Fire on every new feedback. Slack + Discord auto-formatted.</p>
      </div>
      <WebhooksClient boardId={board.id} initial={hooks} />
    </div>
  );
}
