"use client";

import { useActionState } from "react";
import { changePasswordAction, type AccountState } from "./actions";

export function ChangePasswordForm() {
  const [state, formAction, pending] = useActionState<AccountState, FormData>(
    changePasswordAction,
    {},
  );

  return (
    <form action={formAction} className="flex flex-col gap-4" noValidate>
      {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}

      {state.success ? (
        <div
          role="status"
          className="rounded-2xl border px-4 py-3 text-sm font-semibold"
          style={{
            borderColor: "rgba(158,215,255,.32)",
            background: "rgba(158,215,255,.08)",
            color: "#d6ecff",
          }}
        >
          Passwort erfolgreich geändert.
        </div>
      ) : null}

      <div className="field">
        <label className="label" htmlFor="currentPassword">
          Aktuelles Passwort
        </label>
        <input
          id="currentPassword"
          name="currentPassword"
          type="password"
          autoComplete="current-password"
          required
          className="input"
        />
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div className="field">
          <label className="label" htmlFor="newPassword">
            Neues Passwort
          </label>
          <input
            id="newPassword"
            name="newPassword"
            type="password"
            autoComplete="new-password"
            required
            className="input"
          />
        </div>
        <div className="field">
          <label className="label" htmlFor="confirmPassword">
            Bestätigen
          </label>
          <input
            id="confirmPassword"
            name="confirmPassword"
            type="password"
            autoComplete="new-password"
            required
            className="input"
          />
        </div>
      </div>

      <div>
        <button type="submit" className="btn btn-primary" disabled={pending}>
          {pending ? "Speichern …" : "Passwort ändern"}
        </button>
      </div>
    </form>
  );
}
