import { useState } from "react";
import { login, type AuthUser } from "./api";

// 管理端登录门：登录成功回调 onAuthed。需管理员账号（生产须在 ADMIN_USER_IDS 白名单）。
export function Login({ onAuthed }: { onAuthed: (u: AuthUser) => void }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const submit = async () => {
    if (busy || !email.trim() || !password) return;
    setErr("");
    setBusy(true);
    try {
      onAuthed(await login(email.trim(), password));
    } catch (e) {
      setErr((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="flex h-screen w-screen items-center justify-center bg-gray-50 text-gray-900">
      <div className="w-[340px] rounded-xl border bg-white p-6 shadow-sm">
        <div className="text-sm font-bold text-gray-800">sundynix-agentix</div>
        <div className="mb-5 text-[11px] text-gray-400">运维控制台 · 管理员登录</div>
        <label className="mb-1 block text-xs text-gray-500">邮箱</label>
        <input
          className="mb-3 w-full rounded border px-3 py-2 text-sm focus:border-violet-500 focus:outline-none"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="admin@example.com"
          autoFocus
          onKeyDown={(e) => e.key === "Enter" && submit()}
        />
        <label className="mb-1 block text-xs text-gray-500">密码</label>
        <input
          className="mb-4 w-full rounded border px-3 py-2 text-sm focus:border-violet-500 focus:outline-none"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="••••••••"
          onKeyDown={(e) => e.key === "Enter" && submit()}
        />
        {err && <div className="mb-3 rounded bg-rose-50 px-3 py-2 text-xs text-rose-600">{err}</div>}
        <button
          className="w-full rounded bg-violet-600 py-2 text-sm font-medium text-white hover:bg-violet-700 disabled:opacity-50"
          disabled={busy || !email.trim() || !password}
          onClick={submit}
        >
          {busy ? "登录中…" : "登录"}
        </button>
        <p className="mt-3 text-[10px] leading-relaxed text-gray-400">
          需管理员账号。开发期任意已注册账号即可；生产期账号须在网关 ADMIN_USER_IDS 白名单内。
        </p>
      </div>
    </div>
  );
}
