import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";

import { prisma } from "@/lib/prisma";
import { getSession } from "@/lib/auth";
import { redirect } from "next/navigation";

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

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

  const tenantFilter = session.role === "super_admin" ? {} : { tenantId: session.tenantId };

  const [pendingCount, openCount, agentCount, unassignedCount] = await Promise.all([
    prisma.conversation.count({ where: { ...tenantFilter, status: "PENDING" } }),
    prisma.conversation.count({ where: { ...tenantFilter, status: "OPEN" } }),
    prisma.user.count({ where: { ...tenantFilter, role: { code: "AGENT" } } }),
    prisma.conversation.count({ where: { ...tenantFilter, assignedUserId: null, status: { in: ["OPEN", "PENDING"] } } })
  ]);

  const autoRuleSuggestion =
    agentCount > 0
      ? `Round-robin aktif (${agentCount} agent): prioritas agent akan otomatis berputar saat penugasan masuk.`
      : "Tambahkan agent terlebih dahulu sebelum auto-assignment dapat berjalan penuh.";

  return (
    <ShellPage shell="admin" title="Auto Assignment Rules" description="Pengaturan distribusi percakapan dan ringkasan antrean.">
      <SectionCard title="Auto assignment status">
        <div className="grid gap-4 md:max-w-2xl">
          <p className="text-sm text-on-surface-variant">Auto-assign belum memiliki field konfigurasi per tenant di DB saat ini.</p>
          <p className="text-sm text-on-surface">
            Open: {openCount} • Pending: {pendingCount} • Unassigned: {unassignedCount} • Agent aktif: {agentCount}
          </p>
          <p className="text-sm">{autoRuleSuggestion}</p>
          <p className="rounded-xl border border-line bg-surface-container p-3 text-sm text-on-surface-variant">
            Rekomendasi rule: utamakan penugasan ke agent dengan beban kerja paling rendah dari hitungan `open + pending`.
          </p>
          <div>
            <Button href="/settings">Back to Settings</Button>
          </div>
        </div>
      </SectionCard>
    </ShellPage>
  );
}
