"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";

export default function SoftLaunchLoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const next = searchParams.get("next")?.trim() || "/internal/soft-launch";
  const [secret, setSecret] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const res = await fetch("/api/internal/soft-launch/gate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ secret }),
      });
      if (!res.ok) {
        const j = (await res.json().catch(() => ({}))) as { message?: string };
        setError(j.message ?? `Lỗi ${res.status}`);
        return;
      }
      router.push(next.startsWith("/") ? next : "/internal/soft-launch");
      router.refresh();
    } catch {
      setError("Không gọi được máy chủ web.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={(ev) => void onSubmit(ev)} className="mx-auto max-w-md space-y-4 rounded-lg border border-stone-700/50 bg-stone-950/80 p-6">
      <h1 className="font-sans text-lg text-stone-100">Đăng nhập nội bộ (soft launch)</h1>
      <p className="font-sans text-xs leading-relaxed text-stone-400">
        Dùng cùng giá trị <code className="text-stone-300">SOFT_LAUNCH_ADMIN_SECRET</code> như trên backend. Cookie httpOnly, 12 giờ.
      </p>
      <label className="block space-y-1">
        <span className="font-sans text-xs text-stone-500">Mật khẩu nội bộ</span>
        <input
          type="password"
          autoComplete="off"
          value={secret}
          onChange={(e) => setSecret(e.target.value)}
          className="w-full rounded border border-stone-600 bg-stone-900 px-3 py-2 font-mono text-sm text-stone-100"
        />
      </label>
      {error ? <p className="font-sans text-sm text-red-300">{error}</p> : null}
      <button
        type="submit"
        disabled={busy || !secret.trim()}
        className="rounded bg-stone-200 px-4 py-2 font-sans text-sm text-stone-900 disabled:opacity-40"
      >
        {busy ? "Đang xác thực…" : "Tiếp tục"}
      </button>
    </form>
  );
}
