import { redirect } from "next/navigation";
import { apiFetch, getCurrentUser } from "@/lib/api";
import { getDict } from "@/lib/i18n";

export const dynamic = "force-dynamic";

interface AuditRow {
  id: number;
  occurred_at: string;
  action: string;
  entity_type: string | null;
  entity_id: number | null;
  actor_username: string | null;
  ip_address: string | null;
}

function fmt(iso: string): string {
  return new Intl.DateTimeFormat("ar-EG", {
    dateStyle: "short",
    timeStyle: "medium",
    timeZone: "Africa/Cairo",
  }).format(new Date(iso));
}

export default async function AuditPage() {
  const t = await getDict();
  const user = await getCurrentUser();
  if (!user) redirect("/login");
  if (!user.permissions.includes("admin.audit.view")) {
    return (
      <div className="rounded-xl border border-slate-200 bg-white p-10 text-center shadow-card">
        <p className="font-bold text-slate-700">{t.audit.noPerm}</p>
        <p className="mt-1 text-sm text-slate-400">{t.audit.permHint} <code dir="ltr">admin.audit.view</code></p>
      </div>
    );
  }

  const { status, data } = await apiFetch<{ items: AuditRow[] }>("/api/audit?pageSize=50");
  const items = status === 200 ? (data?.items ?? []) : [];

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-extrabold text-slate-900">{t.audit.title}</h1>
        <p className="mt-1 text-sm text-slate-500">
          {t.audit.subtitle}
        </p>
      </header>

      <div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-card">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[720px] text-sm">
            <thead>
              <tr className="border-b border-slate-200 bg-slate-50 text-right text-xs font-bold text-slate-500">
                <th className="px-4 py-3">{t.audit.event}</th>
                <th className="px-4 py-3">{t.audit.actor}</th>
                <th className="px-4 py-3">{t.audit.entity}</th>
                <th className="px-4 py-3">{t.audit.time}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {items.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-4 py-10 text-center text-slate-400">{t.audit.empty}</td>
                </tr>
              )}
              {items.map((a) => (
                <tr key={a.id} className="hover:bg-slate-50/60">
                  <td className="px-4 py-3">
                    <code className="numeric rounded bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-700" dir="ltr">
                      {a.action}
                    </code>
                  </td>
                  <td className="px-4 py-3 text-slate-600" dir="ltr">{a.actor_username ?? "—"}</td>
                  <td className="px-4 py-3 text-xs text-slate-400" dir="ltr">
                    {a.entity_type ?? "—"}
                    {a.entity_id != null ? `#${a.entity_id}` : ""}
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500">{fmt(a.occurred_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
