import Link from "next/link";
import { requireSession } from "@/lib/auth";
import { listInviteEvents } from "@/lib/invite-events";
import { formatDate } from "@/lib/format";
import { PageHeader, TableWrap, EmptyState } from "@/components/ui";
import { CreateInviteEventForm } from "./create-form";

export const dynamic = "force-dynamic";

export default async function InviteEventsPage() {
  const session = await requireSession();
  const events = await listInviteEvents(session);

  return (
    <>
      <PageHeader
        title="Sự kiện mời khách"
        subtitle="Sự kiện được giao chỉ tiêu mời khách theo khu vực — khác với Chuyên đề/Lớp học thường, loại này không thường xuyên nhưng cần theo dõi chỉ tiêu và khách CME/chứng nhận."
        actions={
          <Link href="/danh-muc" className="btn-ghost">
            ← Danh mục
          </Link>
        }
      />

      {session.role === "DIRECTOR" && <CreateInviteEventForm />}

      <div className="mt-5">
        {events.length === 0 ? (
          <EmptyState
            message="Chưa có sự kiện nào."
            hint={session.role === "DIRECTOR" ? "Tạo sự kiện ở trên để bắt đầu giao chỉ tiêu." : "Ban giám đốc chưa tạo sự kiện nào."}
          />
        ) : (
          <TableWrap>
            <thead>
              <tr>
                <th>Sự kiện</th>
                <th>Ngày sự kiện</th>
                <th>Hạn chót mời</th>
                <th>Ghi chú</th>
              </tr>
            </thead>
            <tbody>
              {events.map((e) => (
                <tr key={e.id}>
                  <td>
                    <Link href={`/danh-muc/su-kien-moi-khach/${e.id}`} className="font-medium text-ink-700 hover:text-brand-600">
                      {e.name}
                    </Link>
                  </td>
                  <td className="tnum whitespace-nowrap text-ink-500">{formatDate(e.eventDate)}</td>
                  <td className="tnum whitespace-nowrap text-ink-500">{formatDate(e.inviteDeadline ?? e.eventDate)}</td>
                  <td className="text-ink-500">{e.note || "—"}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        )}
      </div>
    </>
  );
}
