"use client";

import { useId, useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import { validationA11yProps } from "./model";
export function PasswordField({
  label,
  value,
  onChange,
  autoComplete = "new-password",
  disabled = false,
  error,
  maxLength = 1024,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  autoComplete?: string;
  disabled?: boolean;
  error?: string;
  maxLength?: number;
}) {
  const id = useId();
  const [visible, setVisible] = useState(false);
  return (
    <div>
      <label htmlFor={id} className="field-label">
        {label} *
      </label>
      <div className="relative">
        <input
          id={id}
          className="form-input pr-12"
          type={visible ? "text" : "password"}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          autoComplete={autoComplete}
          disabled={disabled}
          maxLength={maxLength}
          {...validationA11yProps(error, `${id}-error`)}
          required
        />
        <button
          type="button"
          disabled={disabled}
          className="absolute top-0 right-0 flex h-11 w-11 items-center justify-center text-muted-foreground"
          onClick={() => setVisible(!visible)}
          aria-label={`${visible ? "Hide" : "Show"} ${label.toLowerCase()}`}
        >
          {visible ? <EyeOff size={18} /> : <Eye size={18} />}
        </button>
      </div>
      {error && (
        <p id={`${id}-error`} role="alert" className="mt-1 text-xs text-destructive">
          {error}
        </p>
      )}
    </div>
  );
}
