import Link from "next/link";
import { redirect } from "next/navigation";

import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";

function previewText(value: string | null | undefined) {
  if (!value) {
    return "-";
  }
  return value.length > 40 ? `${value.slice(0, 40)}...` : value;
}

export default async function CannedResponsesPage() {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const templates = await prisma.messageTemplate.findMany({
    where: { tenantId: session.tenantId },
    orderBy: { createdAt: "desc" }
  });

  return (
    <ShellPage shell="admin" title="Canned Responses" description="Library jawaban cepat untuk agent dan admin.">
      <TablePlaceholder
        title="Responses"
        columns={["Template", "Category", "Status", "Preview"]}
        rows={templates.map((template) => [
          template.name,
          template.category,
          template.approvalStatus,
          <div key={template.id} className="space-y-1">
            <p>{previewText(template.bodyText)}</p>
            <Link href={`/templates/${template.id}`} className="text-xs text-brand hover:underline">
              Open
            </Link>
          </div>
        ])}
      />
    </ShellPage>
  );
}
