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

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

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

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

  const contacts = await prisma.contact.findMany({
    where: { tenantId: session.tenantId },
    include: {
      contactTags: {
        include: { tag: true }
      }
    },
    orderBy: { lastInteractionAt: "desc" }
  });

  const rows = contacts.map((contact) => [
    contact.fullName,
    contact.phoneNumber,
    contact.lastInteractionAt ? new Intl.DateTimeFormat("id-ID", { hour: "2-digit", minute: "2-digit" }).format(contact.lastInteractionAt) : "-"
    ,
    <Link key={contact.id} href={`/contacts/${contact.id}`} className="text-brand hover:underline">
      View
    </Link>
  ]);

  return (
    <ShellPage shell="agent" title="Contacts" description="View contact terbatas untuk kebutuhan handling conversation.">
      <TablePlaceholder
        title="Contacts"
        columns={["Name", "Phone", "Last interaction", "Action"]}
        rows={rows}
      />
    </ShellPage>
  );
}
