import Link from "next/link";
import { and, asc, desc, eq, inArray } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { visibleTerritoryIds } from "@/lib/rbac";
import { canManageEvents, eventOwnerOptions, eventScope } from "@/lib/events-scope";
import { db } from "@/db";
import { events, territories } from "@/db/schema";
import { today } from "@/lib/period";
import { PageHeader, EmptyState } from "@/components/ui";
import { EventManager, type EventRow } from "./event-form";
import { deleteEventAction } from "./actions";

export const dynamic = "force-dynamic";

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

  if (!(await canManageEvents(session))) {
    return (
      <>
        <PageHeader title="Chuyên đề &amp; lớp học" />
        <EmptyState
          message="Bạn không có quyền quản lý chuyên đề."
          hint="Chức năng này dành cho Ban giám đốc, Giám đốc khu vực, Quản lý và nhân viên chuyên môn."
        />
      </>
    );
  }

  // Quản lý chỉ thấy lớp trong phạm vi của mình (nhân viên chuyên môn: lớp của chính họ); người phụ trách và khu vực để chọn cũng chỉ trong phạm vi.
  const isSpecialistSelf = session.role === "SALES";
  const visibleAreas = isSpecialistSelf ? null : await visibleTerritoryIds(session);
  const [rows, territoryRows, staffRows] = await Promise.all([
    db
      .select()
      .from(events)
      .where(await eventScope(session, "edit"))
      .orderBy(desc(events.eventDate))
      .limit(200),
    db
      .select({ id: territories.id, name: territories.name })
      .from(territories)
      .where(
        and(
          eq(territories.tenantId, session.tenantId),
          eq(territories.isActive, true),
          inArray(territories.level, ["REGION", "PROVINCE"]),
          visibleAreas ? inArray(territories.id, visibleAreas.length > 0 ? visibleAreas : ["00000000-0000-0000-0000-000000000000"]) : undefined,
        ),
      )
      .orderBy(asc(territories.code)),
    eventOwnerOptions(session),
  ]);

  const eventRows: EventRow[] = rows.map((row) => ({
    id: row.id,
    name: row.name,
    eventDate: row.eventDate,
    kind: row.kind,
    territoryId: row.territoryId,
    ownerId: row.ownerId,
    invitedCount: row.invitedCount,
    attendedCount: row.attendedCount,
    resultOrderCount: row.resultOrderCount,
    resultRevenue: Number(row.resultRevenue),
    note: row.note,
  }));

  return (
    <>
      <PageHeader
        title="Chuyên đề &amp; lớp học"
        subtitle="Số lượng mời, số lượng tham dự và kết quả đạt được — hiện trong báo cáo chuyển giao (Báo cáo → Chuyển giao)."
        actions={
          <Link href="/danh-muc" className="btn-ghost">
            ← Danh mục
          </Link>
        }
      />
      <EventManager
        rows={eventRows}
        territories={territoryRows}
        staff={staffRows}
        today={today()}
        territoryNames={Object.fromEntries(territoryRows.map((t) => [t.id, t.name]))}
        staffNames={Object.fromEntries(staffRows.map((s) => [s.id, s.name]))}
        onDelete={deleteEventAction}
        ownerLocked={isSpecialistSelf}
      />
    </>
  );
}
