import { type ReactElement, useState } from "react";
import * as React from "react";
import { EyeIcon, EyeOffIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";

/**
 * PasswordInput — shadcn/WealthX
 * The base Input with an integrated show/hide eye toggle (adds right padding for the button).
 *
 * Atom. Presentational and unopinionated — no label, no built-in validation, no strength popover.
 * Controlled or uncontrolled like a native input; wrap in Field/Label/FieldError for composition.
 *
 * NOTE: distinct from `PasswordField` (signup-form-primitives) which is a higher-level *molecule*
 * that bundles Field + Label + fixed "min 8" validation + optional strength popover. Use this atom
 * when you need a password input with a reveal toggle but your own label/validation (e.g. the
 * current/confirm fields of a Change Password form).
 */
export type PasswordInputProps = Omit<React.ComponentProps<"input">, "type"> & {
  /** aria-label for the show/hide toggle button. Default "Show password". */
  toggleAriaLabel?: string;
};

const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
  function PasswordInput(
    { className, toggleAriaLabel = "Show password", disabled, ...props },
    ref,
  ): ReactElement {
    const [visible, setVisible] = useState(false);

    return (
      <div className="relative w-full" data-slot="password-input">
        <Input
          ref={ref}
          type={visible ? "text" : "password"}
          disabled={disabled}
          className={cn("pr-9", className)}
          {...props}
        />
        <button
          type="button"
          tabIndex={-1}
          aria-label={visible ? "Hide password" : toggleAriaLabel}
          aria-pressed={visible}
          disabled={disabled}
          onClick={() => setVisible((v) => !v)}
          className={cn(
            "absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50",
            "focus-visible:outline-none focus-visible:text-primary",
          )}
          data-slot="password-input-toggle"
        >
          {visible ? (
            <EyeOffIcon className="size-4" />
          ) : (
            <EyeIcon className="size-4" />
          )}
        </button>
      </div>
    );
  },
);

export { PasswordInput };
