"use client";

import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
import { FormEvent, useState } from "react";

export function AdminLoginForm() {
  const t = useTranslations("admin");
  const router = useRouter();
  const [err, setErr] = useState(false);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setErr(false);
    const fd = new FormData(e.currentTarget);
    const password = String(fd.get("password"));

    try {
      const res = await fetch("/api/admin/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
      });
      if (!res.ok) {
        setErr(true);
        return;
      }
      router.push("/admin");
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="mx-auto max-w-sm px-4 py-20">
      <h1 className="font-[family-name:var(--font-display)] text-3xl text-foreground">
        {t("loginTitle")}
      </h1>
      <p className="mt-2 text-sm text-muted">{t("loginSubtitle")}</p>
      <form onSubmit={onSubmit} className="mt-8 space-y-4">
        <div>
          <label className="mb-1 block text-sm text-muted">{t("password")}</label>
          <input
            required
            type="password"
            name="password"
            autoComplete="current-password"
            className="w-full rounded-md border border-border bg-card px-3 py-2 text-foreground focus:border-gold focus:outline-none focus:ring-1 focus:ring-gold"
          />
        </div>
        {err && (
          <p className="text-sm text-red-400" role="alert">
            {t("badPassword")}
          </p>
        )}
        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-md bg-gold py-3 text-sm font-medium text-background hover:bg-gold-hover disabled:opacity-60"
        >
          {loading ? "…" : t("signIn")}
        </button>
      </form>
    </div>
  );
}
