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

interface AdminUser {
  id: string;
  email: string;
  displayName: string;
  role: string;
  onboardingCompleted: boolean;
  createdAt: string;
  deletedAt: string | null;
}

export function UsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [search, setSearch] = useState("");
  const [error, setError] = useState<string | null>(null);

  const load = (q = "") => {
    api<{ users: AdminUser[] }>(`/admin/v1/users?search=${encodeURIComponent(q)}`)
      .then((r) => setUsers(r.users))
      .catch((e) => setError(String(e.message)));
  };
  useEffect(() => load(), []);

  return (
    <div>
      <h2>Användare</h2>
      <div className="row" style={{ marginBottom: "1rem" }}>
        <input
          placeholder="Sök e-post …"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && load(search)}
        />
        <button className="ghost" onClick={() => load(search)}>
          Sök
        </button>
      </div>
      {error && <div className="error-text">{error}</div>}
      <div className="panel">
        <table>
          <thead>
            <tr>
              <th>E-post</th>
              <th>Namn</th>
              <th>Roll</th>
              <th>Onboarding</th>
              <th>Skapad</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id}>
                <td>{u.email}</td>
                <td>{u.displayName}</td>
                <td>
                  <span className={`badge ${u.role === "admin" ? "warn" : ""}`}>{u.role}</span>
                </td>
                <td>{u.onboardingCompleted ? "✓" : "–"}</td>
                <td>{new Date(u.createdAt).toLocaleDateString("sv-SE")}</td>
                <td>
                  {u.deletedAt ? (
                    <span className="badge err">raderad</span>
                  ) : (
                    <span className="badge ok">aktiv</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
