import { useEffect, useState } from "react";
import { api } from "../services/api";

export default function UsersPage() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState({});

  async function loadUsers() {
    setLoading(true);
    const data = await api.getUsers();
    setUsers(data);
    setLoading(false);
  }

  useEffect(() => {
    const data = api.getUsers();
    setUsers(data);
    setLoading(false);
  }, []);

  async function saveEmail(id) {
    const email = editing[id]?.trim();
    if (!email) return;
    await api.updateUserEmail(id, email);
    setEditing((prev) => ({ ...prev, [id]: "" }));
    await loadUsers();
  }

  async function deleteUser(id) {
    if (!confirm("Delete this user?")) return;
    await api.deleteUser(id);
    await loadUsers();
  }

  return (
    <section>
      <h2>Manage Users</h2>

      <div className="list">
        {loading ? (
          <p>Loading...</p>
        ) : users.length === 0 ? (
          <p>No users found.</p>
        ) : (
          users.map((user) => (
            <div className="card row" key={user.id}>
              <div className="userEdit">
                <div className="muted">User ID: {user.id.slice(0, 8)}...</div>
                <input
                  value={editing[user.id] ?? user.email}
                  onChange={(e) =>
                    setEditing((prev) => ({ ...prev, [user.id]: e.target.value }))
                  }
                />
              </div>

              <div className="actions">
                <button className="btn primary" onClick={() => updateUserEmail(user.id)}>
                  Save
                </button>
                <button className="btn danger" onClick={() => deleteUser(user.id)}>
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </section>
  );
}