// @File: src/pages/admin/cms/whatsapp/CmsWhatsappAuditLog.tsx
// @Desc: Read-only WhatsApp admin log viewer — two tabs:
//        1. Admin audit (who did what from the CMS).
//        2. Upstream API log (every proxied call to the WhatsApp server).
import { useEffect, useState } from "react";
import { FileSearch, Loader2, RefreshCw } from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge } from "../ui";
import {
  waAdminApiLog,
  waAdminAuditLog,
  type WhatsappApiLogEntry,
  type WhatsappAuditLogEntry,
} from "@/lib/whatsappApi";

type Tab = "audit" | "api";

function fmtDate(iso: string): string {
  try {
    return new Date(iso).toLocaleString();
  } catch {
    return iso;
  }
}

function statusTone(code: number | null): "green" | "amber" | "red" | "slate" {
  if (code == null) return "slate";
  if (code >= 500) return "red";
  if (code >= 400) return "amber";
  if (code >= 200) return "green";
  return "slate";
}

export default function CmsWhatsappAuditLog() {
  const [tab, setTab] = useState<Tab>("audit");
  const [audit, setAudit] = useState<WhatsappAuditLogEntry[]>([]);
  const [api, setApi] = useState<WhatsappApiLogEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = async (which: Tab) => {
    setLoading(true);
    setError(null);
    try {
      if (which === "audit") {
        const rows = await waAdminAuditLog(200);
        setAudit(rows);
      } else {
        const rows = await waAdminApiLog(200);
        setApi(rows);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load log");
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <CmsLayout>
      <PageHeader
        icon={<FileSearch className="w-6 h-6" />}
        title="WhatsApp Audit & API Log"
        description="Every admin change and every upstream WhatsApp API call — for debugging and compliance."
      />

      <SectionCard
        title="Log"
        description="Most recent 200 events. Switch tabs below."
        actions={
          <button
            type="button"
            onClick={() => void load(tab)}
            className="px-3 py-2 rounded-lg border border-slate-300 bg-white text-xs font-semibold text-slate-700 hover:bg-slate-100 transition inline-flex items-center gap-2"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
        }
      >
        <div className="flex gap-1 border-b border-slate-200">
          {[
            { id: "audit", label: "Admin Audit" },
            { id: "api", label: "Upstream API" },
          ].map((t) => (
            <button
              key={t.id}
              type="button"
              onClick={() => setTab(t.id as Tab)}
              className={`px-4 py-2 text-sm font-semibold rounded-t-lg -mb-px border-b-2 ${
                tab === t.id
                  ? "border-[#0b6e3e] text-[#0b6e3e] bg-emerald-50"
                  : "border-transparent text-slate-500 hover:text-slate-700"
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {error && (
          <div className="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
            {error}
          </div>
        )}

        {loading ? (
          <div className="p-6 text-center text-slate-500">
            <Loader2 className="w-4 h-4 animate-spin inline mr-2" /> Loading…
          </div>
        ) : tab === "audit" ? (
          <div className="overflow-x-auto rounded-xl border border-slate-200">
            <table className="min-w-full text-sm">
              <thead className="bg-slate-50 text-slate-600">
                <tr>
                  <th className="text-left p-3 font-semibold">When</th>
                  <th className="text-left p-3 font-semibold">Actor</th>
                  <th className="text-left p-3 font-semibold">Action</th>
                  <th className="text-left p-3 font-semibold">Target</th>
                  <th className="text-left p-3 font-semibold">Detail</th>
                </tr>
              </thead>
              <tbody>
                {audit.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="p-6 text-center text-slate-500">
                      No admin activity yet.
                    </td>
                  </tr>
                ) : (
                  audit.map((r) => (
                    <tr key={r.id} className="border-t border-slate-200">
                      <td className="p-3 align-top text-xs text-slate-600 whitespace-nowrap">
                        {fmtDate(r.created_at)}
                      </td>
                      <td className="p-3 align-top">
                        <div className="text-sm font-semibold text-slate-900">
                          {r.actor_email ?? "—"}
                        </div>
                        {r.actor_user_id && (
                          <div className="text-[11px] text-slate-400 font-mono">
                            {r.actor_user_id}
                          </div>
                        )}
                      </td>
                      <td className="p-3 align-top">
                        <Badge tone="slate">{r.action}</Badge>
                      </td>
                      <td className="p-3 align-top text-xs text-slate-600">
                        {r.target_type ? `${r.target_type}#${r.target_id ?? "?"}` : "—"}
                      </td>
                      <td className="p-3 align-top text-xs text-slate-600 max-w-[320px] truncate">
                        {r.detail ?? "—"}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="overflow-x-auto rounded-xl border border-slate-200">
            <table className="min-w-full text-sm">
              <thead className="bg-slate-50 text-slate-600">
                <tr>
                  <th className="text-left p-3 font-semibold">When</th>
                  <th className="text-left p-3 font-semibold">Channel</th>
                  <th className="text-left p-3 font-semibold">Endpoint</th>
                  <th className="text-left p-3 font-semibold">Status</th>
                  <th className="text-left p-3 font-semibold">Latency</th>
                  <th className="text-left p-3 font-semibold">Sub / User</th>
                </tr>
              </thead>
              <tbody>
                {api.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="p-6 text-center text-slate-500">
                      No API calls logged yet.
                    </td>
                  </tr>
                ) : (
                  api.map((r) => (
                    <tr key={r.id} className="border-t border-slate-200">
                      <td className="p-3 align-top text-xs text-slate-600 whitespace-nowrap">
                        {fmtDate(r.created_at)}
                      </td>
                      <td className="p-3 align-top">
                        <Badge tone="slate">{r.channel}</Badge>
                      </td>
                      <td className="p-3 align-top font-mono text-xs text-slate-700 max-w-[320px] truncate">
                        <span className="text-slate-400 mr-2">{r.method}</span>
                        {r.endpoint}
                      </td>
                      <td className="p-3 align-top">
                        <Badge tone={statusTone(r.status_code)}>
                          {r.status_code ?? "ERR"}
                        </Badge>
                        {r.error_detail && (
                          <div className="text-[11px] text-rose-600 mt-0.5 max-w-[260px] truncate">
                            {r.error_detail}
                          </div>
                        )}
                      </td>
                      <td className="p-3 align-top text-xs text-slate-600">
                        {r.duration_ms != null ? `${r.duration_ms} ms` : "—"}
                      </td>
                      <td className="p-3 align-top text-xs text-slate-600">
                        {r.subscription_id ? `#${r.subscription_id}` : "—"}
                        {r.user_id && (
                          <div className="text-[11px] text-slate-400 font-mono">
                            {r.user_id}
                          </div>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </CmsLayout>
  );
}