import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { postJSON } from "../../../api";
import { setToken } from "../../../admin/token";
import { useAdminT } from "../../../admin/useAdminT";
import { useAdminRouterMode } from "../../../adminRouterMode";
import { adminUiPrefix } from "../../../adminPaths";

export function AdminLogin() {
  const t = useAdminT();
  const mode = useAdminRouterMode();
  const nav = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [err, setErr] = useState<string | null>(null);

  return (
    <div className="min-h-[70vh] flex items-center justify-center">
      <form
        className="w-full max-w-md space-y-4 rounded-3xl border border-ark-line bg-ark-panel p-8"
        onSubmit={async (e) => {
          e.preventDefault();
          setErr(null);
          try {
            const r = await postJSON<{ token: string }>("/api/admin/login", {
              email,
              password,
            });
            setToken(r.token);
            nav(mode === "basename" ? "/" : adminUiPrefix);
          } catch (e) {
            setErr(String(e));
          }
        }}
      >
        <h1 className="text-2xl font-bold">{t("adminLoginTitle")}</h1>
        <label className="block text-sm text-neutral-300">
          {t("email")}
          <input
            className="mt-1 w-full rounded-xl border border-ark-line bg-black px-3 py-2"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </label>
        <label className="block text-sm text-neutral-300">
          {t("password")}
          <input
            type="password"
            className="mt-1 w-full rounded-xl border border-ark-line bg-black px-3 py-2"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </label>
        {err ? <div className="text-sm text-red-300">{err}</div> : null}
        <button
          type="submit"
          className="w-full rounded-xl bg-ark-gold py-3 font-semibold text-black"
        >
          {t("login")}
        </button>
      </form>
    </div>
  );
}
