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/stamps");
      } else {
        setError("密钥不正确");
      }
    } catch {
      setError("连接失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center">
      <div className="w-80 bg-white rounded-lg shadow-sm p-6 border border-gray-200">
        <h1 className="text-lg font-semibold text-gray-800 mb-4 text-center">管理后台</h1>
        <div className="space-y-3">
          <input
            type="password"
            value={key}
            onChange={(e) => setKey(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleLogin()}
            placeholder="输入管理密钥"
            className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm
              focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
          />
          {error && <p className="text-sm text-red-500">{error}</p>}
          <button
            onClick={handleLogin}
            disabled={loading || !key}
            className="w-full py-2 bg-blue-600 text-white text-sm rounded-md
              hover:bg-blue-700 disabled:opacity-50 transition-colors"
          >
            {loading ? "验证中..." : "登录"}
          </button>
        </div>
      </div>
    </div>
  );
}
