import { useState } from "react";
import { useAuth } from "../lib/auth";

type RegisterModalProps = {
  onSuccess: () => void;
  onClose: () => void;
};

const phoneRegex = /^1[3-9]\d{9}$/;

export default function RegisterModal({ onSuccess, onClose }: RegisterModalProps) {
  const { register, login } = useAuth();
  const [mode, setMode] = useState<"register" | "login">("register");
  const [username, setUsername] = useState("");
  const [phone, setPhone] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    setError("");

    if (!phoneRegex.test(phone)) {
      setError("请输入正确的手机号");
      return;
    }
    if (mode === "register" && !username.trim()) {
      setError("请输入用户名");
      return;
    }

    setSubmitting(true);
    try {
      if (mode === "register") {
        await register(username.trim(), phone);
      } else {
        await login(phone);
      }
      onSuccess();
    } catch (e) {
      setError(e instanceof Error ? e.message : "操作失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-end justify-center animate-overlay-fade"
      style={{ backgroundColor: "var(--overlay)" }}
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="w-full max-w-lg bg-[var(--bg-cream)] rounded-t-2xl p-6 pb-10 animate-slide-up safe-bottom">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">
            {mode === "register" ? "注册账号" : "登录"}
          </h3>
          <button onClick={onClose} className="text-[var(--text-muted)] p-1">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="space-y-4">
          {mode === "register" && (
            <div>
              <label className="text-sm text-[var(--text-secondary)] mb-1.5 block">用户名</label>
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="请输入用户名"
                maxLength={20}
                className="w-full px-4 py-3 rounded-xl border border-[var(--border-default)]
                  bg-white text-[var(--text-primary)] text-sm
                  focus:outline-none focus:border-[var(--gold)]
                  placeholder:text-[var(--text-muted)]"
              />
            </div>
          )}

          <div>
            <label className="text-sm text-[var(--text-secondary)] mb-1.5 block">手机号</label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))}
              placeholder="请输入手机号"
              className="w-full px-4 py-3 rounded-xl border border-[var(--border-default)]
                bg-white text-[var(--text-primary)] text-sm
                focus:outline-none focus:border-[var(--gold)]
                placeholder:text-[var(--text-muted)]"
            />
          </div>

          {error && <p className="text-sm text-[var(--terracotta)]">{error}</p>}

          <button
            onClick={handleSubmit}
            disabled={submitting}
            className="w-full py-3 rounded-xl text-sm font-medium text-white transition-opacity"
            style={{
              backgroundColor: "var(--terracotta)",
              opacity: submitting ? 0.6 : 1,
            }}
          >
            {submitting ? "请稍候..." : mode === "register" ? "注册" : "登录"}
          </button>

          <p className="text-center text-xs text-[var(--text-muted)]">
            {mode === "register" ? (
              <>
                已有账号？
                <button onClick={() => setMode("login")} className="text-[var(--gold)] ml-1">
                  去登录
                </button>
              </>
            ) : (
              <>
                没有账号？
                <button onClick={() => setMode("register")} className="text-[var(--gold)] ml-1">
                  去注册
                </button>
              </>
            )}
          </p>
        </div>
      </div>
    </div>
  );
}
