import Link from "next/link";

import { PlaceholderActions, ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { deleteTemplate } from "@/lib/admin-crud";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export default async function TemplatesPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const session = await getSession();
  const templates = session
    ? await prisma.messageTemplate.findMany({
        where: { tenantId: session.tenantId },
        include: { channel: true },
        orderBy: { updatedAt: "desc" }
      })
    : [];
  const error = params.error;
  const infoMessage =
    error === "template_not_found" ? "Template tidak ditemukan." : error === "template_in_use" ? "Template masih digunakan campaign." : null;

  return (
    <ShellPage
      shell="admin"
      title="Templates"
      description="Daftar template WhatsApp, approval status, dan akses ke request form."
      actions={<PlaceholderActions primaryHref="/templates/new" primaryLabel="Create template request" />}
    >
      {infoMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{infoMessage}</p> : null}
      <TablePlaceholder
        title="Template list"
        columns={["Name", "Category", "Language", "Channel", "Status", "Actions"]}
        rows={templates.map((template) => [
          template.name,
          template.category,
          template.languageCode,
          template.channel.channelName,
          template.approvalStatus,
          <div key={template.id} className="flex gap-2">
            <Link href={`/templates/${template.id}`} className="text-brand hover:underline">
              Detail
            </Link>
            <Link href={`/templates/${template.id}/edit`} className="text-brand hover:underline">
              Edit
            </Link>
            <form action={deleteTemplate} className="inline">
              <input type="hidden" name="templateId" value={template.id} />
              <button type="submit" className="text-danger hover:underline">
                Delete
              </button>
            </form>
          </div>
        ])}
      />
    </ShellPage>
  );
}
