import { useEffect, useState } from "react";
import { adminWechatUsers, type WechatUserRow } from "../api";

// 平台 · 微信用户：所有微信扫码登录的用户，集中查看。
// 每个用户仍是独立租户/独立积分（各买各的），这里只做统一观测。
const MICRO = 1_000_000;
const credits = (m: number) => (m / MICRO).toLocaleString("zh-CN", { maximumFractionDigits: 2 });

export function WechatUsersPage() {
  const [rows, setRows] = useState<WechatUserRow[]>([]);
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState("");

  useEffect(() => {
    adminWechatUsers()
      .then(setRows)
      .catch((e) => setErr((e as Error).message))
      .finally(() => setLoading(false));
  }, []);

  const copy = (s: string) => {
    void navigator.clipboard?.writeText(s);
    setCopied(s);
    setTimeout(() => setCopied(""), 1200);
  };

  return (
    <div className="space-y-5">
      <div className="border-b border-gray-200 pb-4">
        <h3 className="text-base font-semibold text-gray-800">微信用户</h3>
        <p className="text-xs text-gray-400">
          扫码登录的用户 · 共 {rows.length} 人 · 每人独立租户与积分（各买各的）
        </p>
      </div>

      <div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
        {err && <p className="mb-2 text-xs text-rose-500">{err}</p>}
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-100 text-left text-[11px] uppercase tracking-wide text-gray-400">
              <th className="py-2 pr-3 font-medium">昵称</th>
              <th className="py-2 pr-3 font-medium">OpenID</th>
              <th className="py-2 pr-3 text-right font-medium">积分余额</th>
              <th className="py-2 font-medium">加入时间</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((u) => (
              <tr key={u.id} className="border-b border-gray-50 last:border-0">
                <td className="py-2 pr-3 text-gray-800">{u.name || "—"}</td>
                <td className="py-2 pr-3">
                  {/* openid 长且要复制，点一下复制全串 */}
                  <button
                    onClick={() => copy(u.wechat_openid)}
                    title="点击复制"
                    className="font-mono text-[11px] text-gray-500 hover:text-violet-600"
                  >
                    {copied === u.wechat_openid ? "已复制 ✓" : `${u.wechat_openid.slice(0, 10)}…${u.wechat_openid.slice(-6)}`}
                  </button>
                </td>
                <td className="py-2 pr-3 text-right tabular-nums text-gray-700">{credits(u.balance_micro)}</td>
                <td className="py-2 text-xs text-gray-500">{new Date(u.created_at).toLocaleString("zh-CN")}</td>
              </tr>
            ))}
            {rows.length === 0 && !loading && (
              <tr>
                <td colSpan={4} className="py-8 text-center text-xs text-gray-400">还没有微信用户</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
