'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { formatDate } from '@/lib/format';
import type { AuditItem } from '@/lib/admin/list';

const PER_PAGE = 50;

export function AuditTable({
  initialEntries,
  initialTotal,
}: {
  initialEntries: AuditItem[];
  initialTotal: number;
}) {
  const [entries, setEntries] = useState<AuditItem[]>(initialEntries);
  const [total, setTotal] = useState(initialTotal);
  const [page, setPage] = useState(1);
  const [action, setAction] = useState('');
  const [targetType, setTargetType] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({
        page: String(page),
        perPage: String(PER_PAGE),
      });
      if (action.trim()) params.set('action', action.trim());
      if (targetType.trim()) params.set('target_type', targetType.trim());
      const res = await fetch(`/api/admin/audit?${params.toString()}`, {
        credentials: 'same-origin',
      });
      if (!res.ok) {
        const b = (await res.json().catch(() => ({}))) as { error?: string };
        throw new Error(b.error ?? `Request failed (${res.status})`);
      }
      const data = (await res.json()) as {
        entries: AuditItem[];
        total: number;
      };
      setEntries(data.entries);
      setTotal(data.total);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, [page, action, targetType]);

  // First page is server-rendered; skip the on-mount fetch to avoid racing the
  // SSR session-cookie refresh (which intermittently 401'd).
  const didMount = useRef(false);
  useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;
      return;
    }
    const t = setTimeout(load, 250);
    return () => clearTimeout(t);
  }, [load]);

  const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));

  return (
    <div>
      <h1>Audit log</h1>

      <div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
        <input
          type="text"
          placeholder="Filter action (e.g. tunnel.delete)"
          value={action}
          onChange={(e) => {
            setPage(1);
            setAction(e.target.value);
          }}
          style={{ maxWidth: 240 }}
        />
        <input
          type="text"
          placeholder="Filter target_type (user/tunnel…)"
          value={targetType}
          onChange={(e) => {
            setPage(1);
            setTargetType(e.target.value);
          }}
          style={{ maxWidth: 240 }}
        />
        <button className="secondary btn-sm" type="button" onClick={load}>
          Refresh
        </button>
      </div>

      {error && <p className="error">{error}</p>}

      {loading ? (
        <p className="muted">Loading…</p>
      ) : entries.length === 0 ? (
        <p className="muted">No audit entries.</p>
      ) : (
        <div className="admin-table-wrap">
          <table className="admin-table">
            <thead>
              <tr>
                <th>When</th>
                <th>Actor</th>
                <th>Action</th>
                <th>Target</th>
                <th>Details</th>
              </tr>
            </thead>
            <tbody>
              {entries.map((e) => (
                <tr key={e.id}>
                  <td>{formatDate(e.created_at)}</td>
                  <td style={{ wordBreak: 'break-all' }}>
                    {e.actor_email ?? e.actor_id ?? '—'}
                  </td>
                  <td>{e.action}</td>
                  <td style={{ wordBreak: 'break-all' }}>
                    {e.target_type ? `${e.target_type}:` : ''}
                    {e.target_id ?? ''}
                  </td>
                  <td>
                    <code className="muted">
                      {JSON.stringify(e.details ?? {})}
                    </code>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="row" style={{ marginTop: '1rem' }}>
        <button
          className="secondary btn-sm"
          type="button"
          disabled={page <= 1}
          onClick={() => setPage((p) => Math.max(1, p - 1))}
        >
          Prev
        </button>
        <span className="muted">
          Page {page} of {totalPages} ({total} total)
        </span>
        <button
          className="secondary btn-sm"
          type="button"
          disabled={page >= totalPages}
          onClick={() => setPage((p) => p + 1)}
        >
          Next
        </button>
      </div>
    </div>
  );
}
