import { useState } from "react";
import { authLogin, authRegister, type AuthUser } from "../api";
import { Button, Field, Input } from "../ui";

// 登录/注册一页两态。注册即建个人默认租户（后端现成行为），登录后进壳。
export function AuthPage({ onAuthed }: { onAuthed: (u: AuthUser) => void }) {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

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

  return (
    <div className="flex h-screen w-screen items-center justify-center bg-ink-950">
      <div className="w-[340px] rounded-xl border border-line bg-ink-900 p-6 shadow-card">
        <div className="mb-1 text-lg font-semibold tracking-tight text-slate-100">sundynix</div>
        <p className="mb-5 text-xs text-slate-500">
          {mode === "login" ? "登录以管理你的组织、团队与账单" : "注册后自动创建你的个人工作区"}
        </p>
        <div className="space-y-3">
          {mode === "register" && (
            <Field label="名字（可选）">
              <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="怎么称呼你" />
            </Field>
          )}
          <Field label="邮箱">
            <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" />
          </Field>
          <Field label="密码" hint={mode === "register" ? "至少 6 位" : undefined}>
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && submit()}
              placeholder="••••••"
            />
          </Field>
          {err && <p className="text-xs text-danger">{err}</p>}
          <Button variant="primary" className="w-full" onClick={submit} disabled={busy || !email.trim() || !password}>
            {busy ? "请稍候…" : mode === "login" ? "登录" : "注册"}
          </Button>
        </div>
        <button
          onClick={() => {
            setMode((m) => (m === "login" ? "register" : "login"));
            setErr("");
          }}
          className="mt-4 text-xs text-slate-500 transition hover:text-slate-300">
          {mode === "login" ? "还没有账户？去注册" : "已有账户？去登录"}
        </button>
      </div>
    </div>
  );
}
