"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import type { Locale } from "@/i18n/routes";
import { getDict } from "@/i18n/dictionaries";

export function LoginForm({ locale }: { locale: Locale }) {
  const dict = getDict(locale);
  const router = useRouter();
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch("/api/admin/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
      });
      if (res.status === 429) {
        setError(dict.admin.errorRateLimited);
        return;
      }
      if (!res.ok) {
        setError(dict.admin.errorInvalid);
        return;
      }
      router.push("/admin/dashboard");
      router.refresh();
    } catch {
      setError(dict.admin.errorInvalid);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="ascii-box space-y-4">
      <label className="block">
        <span className="mb-1 block font-mono text-xs uppercase text-muted">{dict.admin.passwordLabel}</span>
        <input
          type="password"
          name="password"
          autoComplete="current-password"
          required
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          disabled={submitting}
          className="w-full border border-hairline bg-[var(--bg-deep)] px-3 py-2 font-mono text-sm text-[var(--fg)] focus:border-accent focus:outline-none"
        />
      </label>
      <button
        type="submit"
        disabled={submitting}
        className="border border-accent bg-accent px-4 py-2 font-mono text-sm uppercase text-[var(--bg)] disabled:opacity-50"
      >
        {submitting ? dict.admin.submitting : dict.admin.submit}
      </button>
      {error ? <p className="text-sm text-[var(--danger)]">{error}</p> : null}
    </form>
  );
}
