import { useEffect, useState } from "react";
import { useAuth } from "../context/AuthContext";
import { fetchUsers, type UserListItem } from "../api";
import { useDocumentTitle } from "../hooks/useDocumentTitle";
import styles from "./AdminUsers.module.css";

export default function AdminUsers() {
  useDocumentTitle("Users — Admin");
  const { token, startImpersonation, user: currentUser } = useAuth();
  const [users, setUsers] = useState<UserListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [impersonating, setImpersonating] = useState<string | null>(null);

  useEffect(() => {
    if (!token) return;
    setLoading(true);
    fetchUsers(token)
      .then(setUsers)
      .catch((e) => setError(e.message || "Failed to load users"))
      .finally(() => setLoading(false));
  }, [token]);

  async function handleViewAs(userId: string) {
    setImpersonating(userId);
    try {
      await startImpersonation(userId);
      // Navigation will happen via auth context update
    } catch (e: any) {
      setError(e.message || "Failed to start impersonation");
      setImpersonating(null);
    }
  }

  if (loading) {
    return (
      <div className={styles.page}>
        <h1 className={styles.title}>Users</h1>
        <p className={styles.loading}>Loading users…</p>
      </div>
    );
  }

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

  return (
    <div className={styles.page}>
      <h1 className={styles.title}>Users</h1>
      {users.length === 0 ? (
        <p className={styles.empty}>No users found.</p>
      ) : (
        <table className={styles.table}>
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id}>
                <td>{u.display_name}</td>
                <td>{u.email}</td>
                <td>
                  <span className={styles.roleBadge} data-role={u.role}>
                    {u.role}
                  </span>
                </td>
                <td>
                  {u.role === "creator" && u.id !== currentUser?.id && (
                    <button
                      className={styles.viewAsBtn}
                      disabled={impersonating === u.id}
                      onClick={() => handleViewAs(u.id)}
                    >
                      {impersonating === u.id ? "Switching…" : "View As"}
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
