"use client";

import { useActionState } from "react";
import { type LoginFormState, loginAction } from "@/server/actions/auth";

const initialState: LoginFormState = { error: null, fieldErrors: {}, email: "" };

export function LoginForm({ next }: { next: string | null }) {
  const [state, formAction, pending] = useActionState(loginAction, initialState);

  return (
    <form action={formAction} className="space-y-5" noValidate>
      {next && <input type="hidden" name="next" value={next} />}

      {state.error && (
        <p
          role="alert"
          className="rounded-chesco-sm border border-chesco-red/40 bg-chesco-red/10 px-4 py-3 text-sm"
        >
          {state.error}
        </p>
      )}

      <div>
        <label htmlFor="email" className="block text-sm font-medium">
          Email
        </label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="username"
          required
          maxLength={254}
          defaultValue={state.email}
          aria-invalid={state.fieldErrors.email ? true : undefined}
          aria-describedby={state.fieldErrors.email ? "email-error" : undefined}
          className="mt-1 block w-full rounded-chesco-sm border border-chesco-border bg-chesco-white px-3 py-2.5 text-base"
        />
        {state.fieldErrors.email && (
          <p id="email-error" className="mt-1 text-sm text-chesco-red">
            {state.fieldErrors.email}
          </p>
        )}
      </div>

      <div>
        <label htmlFor="password" className="block text-sm font-medium">
          Contraseña
        </label>
        <input
          id="password"
          name="password"
          type="password"
          autoComplete="current-password"
          required
          maxLength={128}
          aria-invalid={state.fieldErrors.password ? true : undefined}
          aria-describedby={state.fieldErrors.password ? "password-error" : undefined}
          className="mt-1 block w-full rounded-chesco-sm border border-chesco-border bg-chesco-white px-3 py-2.5 text-base"
        />
        {state.fieldErrors.password && (
          <p id="password-error" className="mt-1 text-sm text-chesco-red">
            {state.fieldErrors.password}
          </p>
        )}
      </div>

      <button
        type="submit"
        disabled={pending}
        className="w-full rounded-chesco-sm bg-chesco-red px-4 py-3 font-display text-sm font-semibold uppercase tracking-wide text-chesco-white transition duration-200 hover:-translate-y-0.5 hover:bg-chesco-red-hover disabled:translate-y-0 disabled:opacity-60"
      >
        {pending ? "Ingresando…" : "Iniciar sesión"}
      </button>
    </form>
  );
}
