"use client";

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

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [totpCode, setTotpCode] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    const res = await fetch("/api/admin/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password, totpCode }),
    });
    setLoading(false);
    if (!res.ok) {
      setError("Incorrect email, password, or 2FA code.");
      return;
    }
    router.push("/admin/games");
  }

  return (
    <div className="mx-auto mt-24 max-w-sm px-4">
      <h1 className="font-display text-2xl font-semibold">Admin sign in</h1>
      <form onSubmit={onSubmit} className="mt-6 space-y-4">
        <Field label="Email">
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full rounded border border-ink-700 bg-ink-900 px-3 py-2"
          />
        </Field>
        <Field label="Password">
          <input
            type="password"
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full rounded border border-ink-700 bg-ink-900 px-3 py-2"
          />
        </Field>
        <Field label="2FA code">
          <input
            type="text"
            inputMode="numeric"
            required
            value={totpCode}
            onChange={(e) => setTotpCode(e.target.value)}
            className="w-full rounded border border-ink-700 bg-ink-900 px-3 py-2"
            placeholder="6-digit code"
          />
        </Field>
        {error && <p className="text-sm text-red-400">{error}</p>}
        <button
          type="submit"
          disabled={loading}
          className="w-full rounded bg-signal px-4 py-2 font-semibold text-ink-950 disabled:opacity-50"
        >
          {loading ? "Signing in…" : "Sign in"}
        </button>
      </form>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block text-sm">
      <span className="mb-1 block text-bone-100/70">{label}</span>
      {children}
    </label>
  );
}
