import { useCallback, useState, type ReactNode } from "react";
import { useNavigate } from "react-router-dom";
import { adminLogin } from "../api";

export function AdminGate({ children }: { children: ReactNode }) {
  const [n, setN] = useState(0);
  const [open, setOpen] = useState(false);
  const [token, setToken] = useState("");
  const navigate = useNavigate();

  const onLogoClick = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      const next = n + 1;
      if (next >= 5) {
        setN(0);
        setOpen(true);
        return;
      }
      setN(next);
      window.setTimeout(() => setN(0), 4000);
    },
    [n]
  );

  const submit = useCallback(async () => {
    const ok = await adminLogin(token);
    if (ok) {
      setOpen(false);
      setToken("");
      navigate("/admin");
      return;
    }
    alert("Token 无效");
  }, [token, navigate]);

  return (
    <>
      <button
        type="button"
        className="admin-gate-logo-btn"
        onClick={onLogoClick}
        aria-label="站点标志"
      >
        {children}
      </button>
      <div id="admin-gate" className="admin-gate" hidden={!open}>
        <div className="admin-gate-panel">
          <input
            id="admin-token"
            type="password"
            autoComplete="off"
            placeholder="Token"
            aria-label="Token"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                submit();
              }
            }}
          />
          <button type="button" id="admin-token-go" onClick={submit}>
            进入
          </button>
          <button
            type="button"
            id="admin-token-cancel"
            onClick={() => setOpen(false)}
          >
            取消
          </button>
        </div>
      </div>
    </>
  );
}
