'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { TableSkeleton } from '@/components/Skeletons';

type LogRow = {
  id: number; action: string; resource: string; userEmail: string | null;
  ipAddress: string; createdAt: string; metadata: unknown;
};

export default function AuditLogsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const [logs, setLogs] = useState<LogRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    adminApiFetch('/admin/audit-logs', accessToken, appSecretProof)
      .then((d) => setLogs(d.logs || []))
      .catch(() => setError('You do not have permission to view this page.'))
      .finally(() => setLoading(false));
  }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  if (error) return <p className="text-sm text-brand-red">{error}</p>;
  if (loading) return <TableSkeleton rows={8} cols={5} />;

  return (
    <div>
      <h1 className="text-lg font-bold mb-4">Audit Logs</h1>
      <div className="bg-white border border-brand-border rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-brand-bg text-left text-xs text-gray-500">
            <tr>
              <th className="px-4 py-2">When</th>
              <th className="px-4 py-2">Actor</th>
              <th className="px-4 py-2">Action</th>
              <th className="px-4 py-2">Resource</th>
              <th className="px-4 py-2">IP</th>
            </tr>
          </thead>
          <tbody>
            {logs.map((l) => (
              <tr key={l.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                <td className="px-4 py-2 text-gray-500">{new Date(l.createdAt).toLocaleString()}</td>
                <td className="px-4 py-2">{l.userEmail ?? 'system'}</td>
                <td className="px-4 py-2"><span className="text-[11px] bg-brand-bg border border-brand-border rounded-full px-2 py-0.5">{l.action}</span></td>
                <td className="px-4 py-2 text-gray-500">{l.resource}</td>
                <td className="px-4 py-2 text-gray-400">{l.ipAddress}</td>
              </tr>
            ))}
            {logs.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-gray-400">No activity logged yet.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}
