"use client";

import { PageHeader, Card, Spinner, ErrorState, Badge } from "@/components/ui";
import { useApi } from "@/hooks/useApi";
import { api } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";

export default function AuditPage() {
  const { t, locale } = useLocale();
  const { data, loading, error, reload } = useApi(() => api.auditLog());

  const fmt = (iso: string) =>
    new Date(iso).toLocaleString(locale === "ar" ? "ar-SA" : "en-GB");

  return (
    <div>
      <PageHeader titleKey="audit.title" />

      {loading && <Spinner />}
      {!loading && !!error && <ErrorState onRetry={reload} />}

      {!loading && !error && (
        <Card className="overflow-x-auto p-0">
          <table className="w-full text-start text-sm">
            <thead className="border-b border-line text-xs text-muted">
              <tr>
                <th className="px-4 py-3 text-start font-medium">{t("audit.when")}</th>
                <th className="px-4 py-3 text-start font-medium">{t("audit.actor")}</th>
                <th className="px-4 py-3 text-start font-medium">{t("audit.action")}</th>
                <th className="px-4 py-3 text-start font-medium">{t("audit.target")}</th>
                <th className="px-4 py-3 text-start font-medium">{t("audit.detail")}</th>
              </tr>
            </thead>
            <tbody>
              {(data ?? []).map((a) => (
                <tr key={a.id} className="border-b border-line last:border-0 align-top">
                  <td className="whitespace-nowrap px-4 py-3 text-xs text-muted">
                    {fmt(a.createdAt)}
                  </td>
                  <td className="px-4 py-3 text-xs">{a.actorEmail ?? "-"}</td>
                  <td className="px-4 py-3">
                    <Badge>{a.action}</Badge>
                  </td>
                  <td className="px-4 py-3 text-xs text-muted">
                    {a.targetType ? `${a.targetType}:${a.targetId ?? ""}` : "-"}
                  </td>
                  <td className="px-4 py-3 text-xs text-muted">{a.detail ?? "-"}</td>
                </tr>
              ))}
              {(data ?? []).length === 0 && (
                <tr>
                  <td colSpan={5} className="px-4 py-10 text-center text-sm text-muted">
                    {t("audit.empty")}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </Card>
      )}
    </div>
  );
}
