import React, { useEffect, useState } from "react";
import { API_BASE, formatUserRegisteredAt } from "../config";
import icons from "../icons";
import AvatarImg from "./AvatarImg";

export default function PublicUserListPage({ onReady, onPreviewImage }) {
  const [users, setUsers] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetch(`${API_BASE}/api/public/users`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "加载用户列表失败");
        if (!cancelled) {
          setUsers(Array.isArray(data.users) ? data.users : []);
          setTotal(Number(data.total) || 0);
        }
      } catch (err) {
        if (!cancelled) setError(err.message);
      } finally {
        if (!cancelled) {
          setLoading(false);
          onReady?.();
        }
      }
    })();
    return () => { cancelled = true; };
  }, [onReady]);

  return (
    <section className="panel public-user-list-page">
      <div className="public-user-list-head">
        <h2 className="public-user-list-title">公开用户</h2>
        <p className="public-user-list-lead">
          按注册时间从早到晚排列（共 {total} 位）
        </p>
      </div>
      {loading && <div className="unified-page-loading">加载中…</div>}
      {!loading && error && (
        <div className="error public-user-list-error" role="alert">{error}</div>
      )}
      {!loading && !error && users.length === 0 && (
        <div className="hint">暂无公开用户</div>
      )}
      {!loading && !error && users.length > 0 && (
        <ul className="public-user-list">
          {users.map((u) => {
            const name = (u.username || "").trim() || u.account;
            const profileUser = {
              account: u.account,
              username: u.username,
              avatarUrl: u.avatarUrl
            };
            return (
              <li key={u.account}>
                <a className="public-user-list-row" href={`/user/${encodeURIComponent(u.account)}`}>
                  <AvatarImg
                    user={profileUser}
                    placeholderSize={56}
                    alt={name}
                    className="public-user-list-avatar previewable-image"
                    previewable
                    onPreviewImage={onPreviewImage}
                    previewLabel={name}
                  />
                  <div className="public-user-list-meta">
                    <span className="public-user-list-name">{name}</span>
                    <span className="public-user-list-account mono">{u.account}</span>
                    <span className="public-user-list-sub">
                      <span className="icon stat-item-icon">{icons.level}</span>
                      Lv.{u.level ?? 0}
                      <span className="public-user-list-sub-sep" aria-hidden />
                      <span className="icon stat-item-icon">{icons.coins}</span>
                      {u.sproutCoins ?? 0}
                      <span className="public-user-list-sub-sep" aria-hidden />
                      注册 {formatUserRegisteredAt(u.createdAt)}
                    </span>
                  </div>
                  <span className="public-user-list-chevron" aria-hidden>›</span>
                </a>
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
}
