"use client";

import { useActionState } from "react";
import { loginAction, type LoginState } from "./actions";

export function LoginForm({ callbackUrl }: { callbackUrl: string }) {
  const [state, formAction, pending] = useActionState<LoginState, FormData>(
    loginAction,
    {},
  );

  return (
    <form action={formAction} className="flex flex-col gap-4" noValidate>
      <input type="hidden" name="callbackUrl" value={callbackUrl} />

      {state.error ? (
        <div
          role="alert"
          className="rounded-2xl border px-4 py-3 text-sm font-semibold"
          style={{
            borderColor: "rgba(255,159,215,.32)",
            background: "rgba(255,159,215,.08)",
            color: "#ffd0ec",
          }}
        >
          {state.error}
        </div>
      ) : null}

      <div className="field">
        <label className="label" htmlFor="email">
          E-Mail-Adresse
        </label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="username"
          required
          className="input"
          placeholder="name@avaria.media"
        />
      </div>

      <div className="field">
        <div className="flex items-center justify-between">
          <label className="label" htmlFor="password">
            Passwort
          </label>
          <a
            href="/reset"
            className="text-xs font-bold text-muted hover:text-[color:var(--blue)] transition-colors"
          >
            Passwort vergessen?
          </a>
        </div>
        <input
          id="password"
          name="password"
          type="password"
          autoComplete="current-password"
          required
          className="input"
          placeholder="••••••••••"
        />
      </div>

      <button type="submit" className="btn btn-primary btn-block mt-1" disabled={pending}>
        {pending ? "Anmelden …" : "Anmelden"}
      </button>
    </form>
  );
}
