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 truncate(value: string, limit: number) {
  return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
}

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

  if (session.role !== "agent") {
    redirect("/unauthorized");
  }

  const tenantId = session.tenantId;
  const [templateCount, activeTemplates, followUpNotes] = await Promise.all([
    prisma.messageTemplate.count({ where: { tenantId } }),
    prisma.messageTemplate.count({ where: { tenantId, approvalStatus: "APPROVED" } }),
    prisma.conversationNote.count({ where: { tenantId, userId: session.userId } })
  ]);

  const totalMessages = await prisma.conversationActivity.count({ where: { tenantId, actorUserId: session.userId } });

  return (
    <ShellPage shell="agent" title="Quick Tools" description="Canned responses, template picker, dan follow-up reminders.">
      <TablePlaceholder
        title="Quick tools"
        columns={["Tool", "Purpose", "Usage", "Action"]}
        rows={[
          [
            "Canned Responses",
            "Shortcuts berbasis template yang paling sering dipakai.",
            truncate(`Total ${totalMessages} log agent activity`, 80),
            <Link key="quick-canned" href="/templates" className="text-brand hover:underline">
              Open templates
            </Link>
          ],
          ["Template Picker", "Pilih template yang sudah disetujui.", `${activeTemplates}/${templateCount} approved`, <Link key="quick-picker" href="/templates" className="text-brand hover:underline">Open templates</Link>],
          ["Follow-up Notes", "Catatan follow-up dari conversation sendiri.", String(followUpNotes), <Link key="quick-followup" href="/agent/inbox" className="text-brand hover:underline">Open inbox</Link>]
        ]}
      />
    </ShellPage>
  );
}
