"use client";

import { forwardRef, useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import styles from "./Input.module.css";

interface PasswordInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label?: string;
  error?: string;
  hint?: string;
}

const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(function PasswordInput(
  { label, error, hint, required, className = "", ...props },
  ref,
) {
  const [visible, setVisible] = useState(false);

  return (
    <div className={styles.field}>
      {label && (
        <label className={styles.label}>
          {label}
          {required && <span className={styles.required}>*</span>}
        </label>
      )}
      <div className={styles.inputWrap}>
        <input
          ref={ref}
          {...props}
          type={visible ? "text" : "password"}
          className={[styles.input, styles.withIconRight, error ? styles.hasError : "", className]
            .filter(Boolean)
            .join(" ")}
          required={required}
        />
        <button
          type="button"
          className={styles.iconRight}
          style={{ pointerEvents: "auto", cursor: "pointer", background: "none", border: "none" }}
          onClick={() => setVisible((v) => !v)}
          aria-label={visible ? "Masquer le mot de passe" : "Afficher le mot de passe"}
        >
          {visible ? <EyeOff size={16} strokeWidth={1.8} /> : <Eye size={16} strokeWidth={1.8} />}
        </button>
      </div>
      {error && <span className={styles.error}>{error}</span>}
      {hint && !error && <span className={styles.hint}>{hint}</span>}
    </div>
  );
});

export default PasswordInput;
