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);
    try {
      const data = await api.getUsers();
      setUsers(data);
    } catch (err) {
      console.error("Failed to load users:", err);
    }
    setLoading(false);
  }

  useEffect(() => {
    loadUsers();
  }, []);

  async function saveUser(id) {
    const email = editing[id]?.email?.trim();
    const name = editing[id]?.name?.trim();
    const payload = {};
    if (email) payload.email = email;
    if (name) payload.name = name;
    if (Object.keys(payload).length === 0) return;

    try {
      await api.updateUser(id, payload);
      setEditing((prev) => {
        const next = { ...prev };
        delete next[id];
        return next;
      });
      await loadUsers();
    } catch (err) {
      console.error("Failed to update user:", err);
    }
  }

  async function deleteUser(id) {
    if (!confirm("Delete this user?")) return;
    try {
      await api.deleteUser(id);
      await loadUsers();
    } catch (err) {
      console.error("Failed to delete user:", err);
    }
  }

  function getFieldValue(user, field) {
    if (editing[user.id]?.[field] !== undefined) return editing[user.id][field];
    return user[field] || "";
  }

  function setFieldValue(user, field, value) {
    setEditing((prev) => ({
      ...prev,
      [user.id]: { ...prev[user.id], [field]: value },
    }));
  }

  function isEditing(user) {
    return editing[user.id] !== undefined;
  }

  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.role?.name || "user"} · ID: {String(user.id).slice(0, 8)}...
                </div>
                <input
                  value={getFieldValue(user, "name")}
                  onChange={(e) => setFieldValue(user, "name", e.target.value)}
                  onFocus={() => {
                    if (!isEditing(user)) {
                      setEditing((prev) => ({
                        ...prev,
                        [user.id]: { name: user.name, email: user.email },
                      }));
                    }
                  }}
                  placeholder="Name"
                />
                <input
                  value={getFieldValue(user, "email")}
                  onChange={(e) => setFieldValue(user, "email", e.target.value)}
                  onFocus={() => {
                    if (!isEditing(user)) {
                      setEditing((prev) => ({
                        ...prev,
                        [user.id]: { name: user.name, email: user.email },
                      }));
                    }
                  }}
                  placeholder="Email"
                />
              </div>

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