import Link from "next/link";
import { asc, eq, sql } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { canManageSettings } from "@/lib/rbac";
import { db } from "@/db";
import { territories, customers } from "@/db/schema";
import { PageHeader, EmptyState } from "@/components/ui";
import { TerritoryTree, type TerritoryNode } from "./territory-tree";
import { renameTerritoryAction, toggleTerritoryActiveAction } from "./actions";

export const dynamic = "force-dynamic";

export default async function TerritoriesPage() {
  const session = await requireSession();

  if (!canManageSettings(session)) {
    return (
      <>
        <PageHeader title="Khu vực" />
        <EmptyState
          message="Bạn không có quyền sửa khu vực."
          hint="Chức năng này chỉ dành cho Ban giám đốc."
        />
      </>
    );
  }

  const rows = await db
    .select({
      id: territories.id,
      code: territories.code,
      name: territories.name,
      level: territories.level,
      parentId: territories.parentId,
      isActive: territories.isActive,
    })
    .from(territories)
    .where(eq(territories.tenantId, session.tenantId))
    .orderBy(asc(territories.code));

  // Đếm khách hàng theo khu vực bằng truy vấn gộp riêng rồi ghép trong JS.
  const counts = await db
    .select({ territoryId: customers.territoryId, count: sql<number>`count(*)::int` })
    .from(customers)
    .where(eq(customers.tenantId, session.tenantId))
    .groupBy(customers.territoryId);

  const countMap = new Map(counts.filter((c) => c.territoryId).map((c) => [c.territoryId!, Number(c.count)]));

  const nodes: TerritoryNode[] = rows.map((row) => ({
    ...row,
    customerCount: countMap.get(row.id) ?? 0,
  }));

  return (
    <>
      <PageHeader
        title="Khu vực"
        subtitle="Bốn cấp Miền → Tỉnh/TP → Quận/Huyện → Phường/Xã. Quản lý vùng thấy dữ liệu của khu vực được giao và mọi cấp con bên dưới."
        actions={
          <Link href="/danh-muc" className="btn-ghost">
            ← Danh mục
          </Link>
        }
      />
      <TerritoryTree
        nodes={nodes}
        onRename={renameTerritoryAction}
        onToggleActive={toggleTerritoryActiveAction}
      />
      <p className="mt-4 text-xs text-ink-400">
        Khu vực ngừng sử dụng sẽ biến khỏi các ô chọn nhưng số liệu lịch sử vẫn đọc được tên — nên
        không xoá hẳn khu vực đã có đơn hàng.
      </p>
    </>
  );
}
