import { useEffect, useState } from "react";
import { useAuth } from "../context/AuthContext";
import { fetchImpersonationLog, type ImpersonationLogEntry } from "../api/auth";
import { useDocumentTitle } from "../hooks/useDocumentTitle";
import styles from "./AdminAuditLog.module.css";

export default function AdminAuditLog() {
  useDocumentTitle("Audit Log — Admin");
  const { token } = useAuth();
  const [entries, setEntries] = useState<ImpersonationLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);

  useEffect(() => {
    if (!token) return;
    setLoading(true);
    setError(null);
    fetchImpersonationLog(token, page)
      .then(setEntries)
      .catch((e) => setError(e.message || "Failed to load audit log"))
      .finally(() => setLoading(false));
  }, [token, page]);

  if (loading) {
    return (
      <div className={styles.page}>
        <h1 className={styles.title}>Audit Log</h1>
        <p className={styles.loading}>Loading audit log…</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.page}>
        <h1 className={styles.title}>Audit Log</h1>
        <p className={styles.error}>{error}</p>
      </div>
    );
  }

  return (
    <div className={styles.page}>
      <h1 className={styles.title}>Audit Log</h1>
      {entries.length === 0 ? (
        <p className={styles.empty}>No impersonation log entries found.</p>
      ) : (
        <table className={styles.table}>
          <thead>
            <tr>
              <th>Date/Time</th>
              <th>Admin</th>
              <th>Target User</th>
              <th>Action</th>
              <th>Write Mode</th>
              <th>IP Address</th>
            </tr>
          </thead>
          <tbody>
            {entries.map((entry) => (
              <tr key={entry.id}>
                <td>{new Date(entry.created_at).toLocaleString()}</td>
                <td>{entry.admin_name}</td>
                <td>{entry.target_name}</td>
                <td>
                  <span className={styles.actionBadge} data-action={entry.action}>
                    {entry.action}
                  </span>
                </td>
                <td>
                  <span
                    className={styles.writeBadge}
                    data-write={entry.write_mode ? "yes" : "no"}
                  >
                    {entry.write_mode ? "Yes" : "No"}
                  </span>
                </td>
                <td className={styles.ip}>{entry.ip_address ?? "—"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      <div className={styles.pagination}>
        <button
          className={styles.pageBtn}
          disabled={page <= 1}
          onClick={() => setPage((p) => Math.max(1, p - 1))}
        >
          ← Previous
        </button>
        <span className={styles.pageNum}>Page {page}</span>
        <button
          className={styles.pageBtn}
          disabled={entries.length === 0}
          onClick={() => setPage((p) => p + 1)}
        >
          Next →
        </button>
      </div>
    </div>
  );
}
