"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";

export function BetaStaffLoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [secret, setSecret] = useState("");
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErr(null);
    setLoading(true);
    try {
      const res = await fetch("/api/internal/beta-visibility/gate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ secret }),
      });
      if (!res.ok) {
        const j = (await res.json().catch(() => null)) as { message?: string } | null;
        setErr(j?.message ?? "Đăng nhập thất bại.");
        return;
      }
      const next = searchParams.get("next")?.trim();
      router.push(next && next.startsWith("/") ? next : "/");
      router.refresh();
    } catch {
      setErr("Không kết nối được máy chủ.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="mt-6 space-y-4">
      <label className="block text-xs text-stone-400">
        Mật khẩu bypass (BETA_STAFF_BYPASS_SECRET)
        <input
          type="password"
          autoComplete="off"
          data-testid="beta-staff-secret-input"
          value={secret}
          onChange={(ev) => setSecret(ev.target.value)}
          className="mt-1.5 w-full rounded border border-stone-700 bg-stone-900 px-3 py-2 text-sm text-stone-100 outline-none focus:border-amber-700/60"
        />
      </label>
      {err ? <p className="text-sm text-red-300/90">{err}</p> : null}
      <button
        type="submit"
        data-testid="beta-staff-login-submit"
        disabled={loading || secret.length < 1}
        className="rounded bg-amber-800/80 px-4 py-2 text-sm text-stone-100 hover:bg-amber-700/90 disabled:opacity-50"
      >
        {loading ? "Đang xác thực…" : "Mở toàn bộ tuyến (staff)"}
      </button>
    </form>
  );
}
