import React, { useEffect, useMemo, useState } from "react";
import AdminPageHeader from "../../components/admin/AdminPageHeader.jsx";
import { openSatPortal } from "../../config/satPortal.js";
import { fetchUsers } from "../../services/swiApi.js";
import { getApiErrorMessage } from "../../utils/apiError.js";

function labelForUser(u) {
  return u.employee_name || u.email_id || `User #${u.user_id}`;
}

export default function AdminUsersPage() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [query, setQuery] = useState("");

  useEffect(() => {
    fetchUsers()
      .then(setUsers)
      .catch((e) =>
        setError(getApiErrorMessage(e, "Could not load users."))
      )
      .finally(() => setLoading(false));
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return users;
    return users.filter((u) => {
      const name = labelForUser(u).toLowerCase();
      const email = (u.email_id || "").toLowerCase();
      const role = (u.role_name || "").toLowerCase();
      return name.includes(q) || email.includes(q) || role.includes(q);
    });
  }, [users, query]);

  return (
    <div className="swi-admin-users">
      <AdminPageHeader
        title="User directory"
        subtitle="Users available for SWI assignment and platform access."
        actions={
          <button
            type="button"
            className="swi-btn swi-btn--ghost"
            onClick={() => openSatPortal("/users")}
          >
            Manage in SAT portal
          </button>
        }
      />

      {error ? (
        <div className="swi-error" role="alert">
          {error}
        </div>
      ) : null}

      <div className="swi-admin-assign-toolbar swi-panel">
        <div className="swi-admin-assign-stats">
          <span className="swi-admin-assign-stat">
            <strong>{users.length}</strong> users
          </span>
        </div>
        <label className="swi-admin-assign-search">
          <span className="visually-hidden">Search users</span>
          <input
            type="search"
            className="swi-input"
            placeholder="Search by name, email, or role…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
      </div>

      <section className="swi-panel swi-admin-assign-content">
        {loading ? (
          <p className="swi-muted swi-admin-assign-empty">Loading users…</p>
        ) : !filtered.length ? (
          <p className="swi-muted swi-admin-assign-empty">
            {users.length ? "No users match your search." : "No users found."}
          </p>
        ) : (
          <div className="swi-table-wrap swi-admin-assign-table-wrap">
            <table className="swi-table swi-admin-assign-table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Role</th>
                  <th>User ID</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((u) => (
                  <tr key={u.user_id}>
                    <td data-label="Name">{labelForUser(u)}</td>
                    <td data-label="Email">{u.email_id || "—"}</td>
                    <td data-label="Role">{u.role_name || "—"}</td>
                    <td data-label="User ID">{u.user_id}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}
