// @File: src/pages/admin/cms/bizmail/CmsBizmailAuditLog.tsx
// @Desc: Read-only table listing every Bizmail360 audit-log entry.
import { useEffect, useState } from "react";
import { FileSearch, Loader2, AlertTriangle, RefreshCw } from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge } from "../ui";
import { adminFetchAuditLog, type BizmailAuditLog } from "@/lib/bizmailApi";

function statusTone(status: string): "green" | "red" | "slate" {
  if (status === "success") return "green";
  if (status === "error") return "red";
  return "slate";
}

export default function CmsBizmailAuditLog() {
  const [rows, setRows] = useState<BizmailAuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await adminFetchAuditLog();
      setRows(list);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load audit log");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  return (
    <CmsLayout>
      <PageHeader
        icon={<FileSearch className="w-6 h-6" />}
        title="Bizmail360 Audit Log"
        description="Every SmarterMail API call issued by this module."
      />

      <SectionCard
        title="Recent Events"
        description={`${rows.length} entries shown (newest first).`}
        actions={
          <button
            onClick={() => void load()}
            disabled={loading}
            className="px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition disabled:opacity-60 inline-flex items-center gap-1.5"
          >
            {loading ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <RefreshCw className="w-3.5 h-3.5" />
            )}
            Refresh
          </button>
        }
      >
        {error && (
          <div className="flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
            <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
            <span>{error}</span>
          </div>
        )}
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading audit log…
          </div>
        ) : rows.length === 0 ? (
          <div className="text-sm text-slate-500">No audit entries yet.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs text-slate-500 uppercase tracking-wider border-b border-slate-200">
                  <th className="py-2 pr-3">Time</th>
                  <th className="py-2 pr-3">Actor</th>
                  <th className="py-2 pr-3">Action</th>
                  <th className="py-2 pr-3">Target</th>
                  <th className="py-2 pr-3">Status</th>
                  <th className="py-2 pr-3">Sub</th>
                  <th className="py-2 pr-3">Error</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr key={r.id} className="border-b border-slate-100 last:border-0 align-top">
                    <td className="py-2 pr-3 whitespace-nowrap text-slate-600">
                      {new Date(r.created_at).toLocaleString()}
                    </td>
                    <td className="py-2 pr-3 text-slate-700">
                      {r.actor_email || r.actor_user_id || "system"}
                    </td>
                    <td className="py-2 pr-3 font-mono text-xs">{r.action}</td>
                    <td className="py-2 pr-3 font-mono text-xs text-slate-500">
                      {r.target || "—"}
                    </td>
                    <td className="py-2 pr-3">
                      <Badge tone={statusTone(r.status)}>{r.status}</Badge>
                    </td>
                    <td className="py-2 pr-3 text-slate-500">
                      {r.subscription_id ?? "—"}
                    </td>
                    <td className="py-2 pr-3 text-rose-600 text-xs max-w-[260px] truncate">
                      {r.error_message || ""}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </CmsLayout>
  );
}