import { useState } from "react";
import { useNavigate } from "react-router-dom";

export default function AdminLogin() {
  const navigate = useNavigate();
  const [key, setKey] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/admin/stats", { headers: { "X-Admin-Key": key } });
      const json = await res.json();
      if (json.success) {
        sessionStorage.setItem("admin_key", key);
        navigate("/admin/dashboard");
      } else {
        setError("密钥不正确");
      }
    } catch {
      setError("连接失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center relative overflow-hidden grain-overlay">
      <div className="absolute inset-0 bg-[var(--bg-dark-deep)]" />
      <div
        className="absolute inset-0"
        style={{
          backgroundImage: `
            radial-gradient(ellipse 60% 50% at 50% 40%, rgba(212, 165, 116, 0.08) 0%, transparent 100%),
            radial-gradient(circle at 15% 80%, rgba(199, 91, 57, 0.06) 0%, transparent 50%),
            radial-gradient(circle at 85% 20%, rgba(45, 106, 79, 0.04) 0%, transparent 40%)
          `,
        }}
      />
      <div
        className="absolute inset-0 opacity-[0.03]"
        style={{
          backgroundImage: `
            linear-gradient(rgba(212, 165, 116, 0.5) 1px, transparent 1px),
            linear-gradient(90deg, rgba(212, 165, 116, 0.5) 1px, transparent 1px)
          `,
          backgroundSize: "60px 60px",
        }}
      />

      <div className="relative z-10 w-full max-w-sm px-6">
        {/* Brand */}
        <div className="text-center mb-10 animate-fade-in">
          <div className="inline-flex items-center gap-3 mb-6">
            <span className="block w-10 h-px bg-[var(--gold)]/50" />
            <span
              className="text-[var(--gold)] text-[11px] tracking-[0.4em] uppercase"
              style={{ fontFamily: "'Playfair Display', serif", fontWeight: 500 }}
            >
              CityWalk · Atelier
            </span>
            <span className="block w-10 h-px bg-[var(--gold)]/50" />
          </div>
          <h1
            className="text-[var(--text-inverted)] text-4xl leading-none mb-3"
            style={{ fontFamily: "'Playfair Display', serif", fontWeight: 700, letterSpacing: "-0.02em" }}
          >
            图章后台
          </h1>
          <p className="text-[var(--gold-light)]/50 text-[11px] tracking-[0.28em] uppercase">
            Stamp · Admin Console
          </p>
        </div>

        {/* Card */}
        <div
          className="relative animate-fade-in-up"
          style={{ animationDelay: "0.15s" }}
        >
          {/* Corner flourishes */}
          <span className="absolute -top-1.5 -left-1.5 w-6 h-6 border-t border-l border-[var(--gold)]/40" />
          <span className="absolute -top-1.5 -right-1.5 w-6 h-6 border-t border-r border-[var(--gold)]/40" />
          <span className="absolute -bottom-1.5 -left-1.5 w-6 h-6 border-b border-l border-[var(--gold)]/40" />
          <span className="absolute -bottom-1.5 -right-1.5 w-6 h-6 border-b border-r border-[var(--gold)]/40" />

          <div
            className="rounded-xl bg-[var(--bg-cream)] p-7"
            style={{ boxShadow: "0 32px 80px rgba(0,0,0,0.4)" }}
          >
            <div className="flex items-center gap-2 mb-5">
              <span className="block w-4 h-px bg-[var(--gold)]" />
              <span
                className="text-[var(--gold)] text-[10px] tracking-[0.32em] uppercase"
                style={{ fontFamily: "'Playfair Display', serif" }}
              >
                Access
              </span>
            </div>

            <label className="block text-[13px] text-[var(--text-secondary)] mb-2">管理密钥</label>
            <input
              type="password"
              value={key}
              onChange={(e) => setKey(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && key && handleLogin()}
              placeholder="••••••••"
              className="w-full px-4 py-3 bg-white border border-[var(--border-default)] rounded-lg text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)]/50 focus:outline-none focus:border-[var(--gold)] focus:ring-2 focus:ring-[var(--gold)]/15 transition-all"
              autoFocus
            />

            {error && (
              <div className="mt-3 flex items-center gap-2 text-[13px] text-[var(--terracotta)]">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4">
                  <circle cx="12" cy="12" r="10" />
                  <path d="M12 8v4M12 16h.01" />
                </svg>
                {error}
              </div>
            )}

            <button
              onClick={handleLogin}
              disabled={loading || !key}
              className="mt-6 w-full py-3 rounded-lg text-white text-sm font-medium transition-all disabled:opacity-40 hover:brightness-110"
              style={{
                backgroundColor: "var(--terracotta)",
                boxShadow: "0 8px 24px rgba(199,91,57,0.35)",
              }}
            >
              {loading ? "验证中..." : "进入后台"}
            </button>

            <div className="mt-6 pt-5 border-t border-[var(--border-muted)]">
              <p className="text-[10px] tracking-[0.25em] uppercase text-[var(--text-muted)] text-center">
                仅限授权访问
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
