"use client";

import { useActionState } from "react";
import { type ChangePasswordState, changePasswordAction } from "@/server/actions/password";
import { PASSWORD_POLICY_MESSAGE } from "@/lib/validation/auth";

const initialState: ChangePasswordState = { error: null };

const FIELDS = [
  { name: "currentPassword", label: "Contraseña actual", autoComplete: "current-password" },
  { name: "newPassword", label: "Nueva contraseña", autoComplete: "new-password" },
  { name: "confirmPassword", label: "Confirmar nueva contraseña", autoComplete: "new-password" },
] as const;

export function ChangePasswordForm() {
  const [state, formAction, pending] = useActionState(changePasswordAction, initialState);
  return (
    <form action={formAction} className="space-y-5">
      {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>
      )}
      {FIELDS.map((field) => (
        <div key={field.name}>
          <label htmlFor={field.name} className="block text-sm font-medium">
            {field.label}
          </label>
          <input
            id={field.name}
            name={field.name}
            type="password"
            autoComplete={field.autoComplete}
            required
            maxLength={128}
            className="mt-1 block w-full rounded-chesco-sm border border-chesco-border px-3 py-2.5 text-base"
          />
        </div>
      ))}
      <p className="text-xs text-chesco-text-muted">{PASSWORD_POLICY_MESSAGE}</p>
      <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:bg-chesco-red-hover disabled:opacity-60"
      >
        {pending ? "Guardando…" : "Guardar contraseña"}
      </button>
    </form>
  );
}
