"use client";

import { useActionState } from "react";
import { loginAction, type LoginState } from "@/lib/admin-actions";

const INITIAL: LoginState = { error: "" };

/** Admin sign-in form. Credentials travel via server action, never localStorage. */
export function LoginForm({ next }: { next: string }) {
  const [state, formAction, pending] = useActionState(loginAction, INITIAL);

  return (
    <form
      action={formAction}
      className="w-full max-w-sm rounded-2xl border border-slate-800 bg-slate-900 p-8"
      aria-describedby={state.error ? "login-error" : undefined}
    >
      <h1 className="text-2xl font-bold text-white">Admin sign in</h1>
      <p className="mt-1 text-sm text-slate-400">
        Restricted area. Activity here is privileged.
      </p>
      <input type="hidden" name="next" value={next} />
      <div className="mt-6 space-y-4">
        <div>
          <label
            htmlFor="username"
            className="mb-1 block text-sm font-medium text-slate-300"
          >
            Username
          </label>
          <input
            id="username"
            name="username"
            type="text"
            autoComplete="username"
            required
            className="h-11 w-full rounded-xl border border-slate-700 bg-slate-950 px-4 text-sm text-white focus:border-brand-500 focus:outline-none"
          />
        </div>
        <div>
          <label
            htmlFor="password"
            className="mb-1 block text-sm font-medium text-slate-300"
          >
            Password
          </label>
          <input
            id="password"
            name="password"
            type="password"
            autoComplete="current-password"
            required
            className="h-11 w-full rounded-xl border border-slate-700 bg-slate-950 px-4 text-sm text-white focus:border-brand-500 focus:outline-none"
          />
        </div>
      </div>
      {state.error ? (
        <p id="login-error" role="alert" className="mt-4 text-sm text-red-400">
          {state.error}
        </p>
      ) : null}
      <button
        type="submit"
        disabled={pending}
        className="mt-6 inline-flex h-11 w-full items-center justify-center rounded-xl bg-brand-600 font-semibold text-white transition-colors hover:bg-brand-500 disabled:opacity-60"
      >
        {pending ? "Signing in…" : "Sign in"}
      </button>
    </form>
  );
}
