// @File: src/pages/admin/cms/cpanel/CmsCpanelAuditLog.tsx
// @Desc: Read-only cPanel audit log + WHM API call log viewer.
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { cpanelAdmin, type CpanelApiLogEntry, type CpanelAuditEntry } from "@/lib/cpanelApi";

export default function CmsCpanelAuditLog() {
  const [audit, setAudit] = useState<CpanelAuditEntry[]>([]);
  const [apiLogs, setApiLogs] = useState<CpanelApiLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const [a, l] = await Promise.all([
          cpanelAdmin.listAuditLog(200),
          cpanelAdmin.listApiLogs({ limit: 200 }),
        ]);
        setAudit(a);
        setApiLogs(l);
      } catch (e) {
        setErr(e instanceof Error ? e.message : "Failed to load");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-2xl font-bold">cPanel Audit & API Log</h1>
      {err && <Alert variant="destructive"><AlertDescription>{err}</AlertDescription></Alert>}

      <Card>
        <CardHeader><CardTitle>Lifecycle audit log</CardTitle></CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : audit.length === 0 ? (
            <p className="text-sm text-muted-foreground">No events yet.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="text-left text-muted-foreground">
                  <tr>
                    <th className="py-2">When</th>
                    <th>Action</th>
                    <th>Admin</th>
                    <th>Target user</th>
                    <th>Account</th>
                    <th>Details</th>
                  </tr>
                </thead>
                <tbody>
                  {audit.map((row) => (
                    <tr key={row.id} className="border-t align-top">
                      <td className="py-2 text-xs text-muted-foreground whitespace-nowrap">
                        {new Date(row.created_at).toLocaleString()}
                      </td>
                      <td><Badge variant="outline">{row.action}</Badge></td>
                      <td className="text-xs">{row.admin_email ?? row.admin_user_id ?? "—"}</td>
                      <td className="text-xs">{row.target_user_id ?? "—"}</td>
                      <td className="text-xs">{row.account_id ?? "—"}</td>
                      <td className="text-xs text-muted-foreground max-w-xs truncate">{row.details ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>WHM API calls</CardTitle></CardHeader>
        <CardContent>
          {apiLogs.length === 0 ? (
            <p className="text-sm text-muted-foreground">No API calls logged.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="text-left text-muted-foreground">
                  <tr>
                    <th className="py-2">When</th>
                    <th>Endpoint</th>
                    <th>Server</th>
                    <th>Status</th>
                    <th>HTTP</th>
                    <th>ms</th>
                    <th>Error</th>
                  </tr>
                </thead>
                <tbody>
                  {apiLogs.map((row) => (
                    <tr key={row.id} className="border-t align-top">
                      <td className="py-2 text-xs text-muted-foreground whitespace-nowrap">
                        {new Date(row.created_at).toLocaleString()}
                      </td>
                      <td className="font-mono text-xs">{row.method} {row.endpoint}</td>
                      <td className="text-xs">{row.server_id ?? "—"}</td>
                      <td>
                        <Badge variant={row.status === "ok" ? "default" : "destructive"}>{row.status}</Badge>
                      </td>
                      <td className="text-xs">{row.http_status ?? "—"}</td>
                      <td className="text-xs">{row.duration_ms ?? "—"}</td>
                      <td className="text-xs text-muted-foreground max-w-xs truncate">{row.error_message ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}