"use client";

import { forwardRef, useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import { useTranslations } from "next-intl";

interface PasswordInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "type"> {
  label?: string;
  error?: string;
}

const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
  ({ label, error, className = "", id, disabled, ...props }, ref) => {
    const t = useTranslations("auth");
    const [visible, setVisible] = useState(false);
    const inputId = id ?? "password";

    return (
      <div className="space-y-1.5">
        {label && (
          <label htmlFor={inputId} className="block text-sm font-medium text-[var(--text-muted)]">
            {label}
          </label>
        )}
        <div className="relative">
          <input
            ref={ref}
            id={inputId}
            type={visible ? "text" : "password"}
            disabled={disabled}
            autoComplete="current-password"
            aria-invalid={error ? true : undefined}
            aria-describedby={error ? `${inputId}-error` : undefined}
            className={`w-full px-3.5 py-2.5 pe-11 bg-[var(--bg-elevated)] border rounded-lg text-[var(--text)] placeholder:text-[var(--text-faint)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/40 focus:border-[var(--accent)]/60 transition text-sm disabled:opacity-60 disabled:cursor-not-allowed ${
              error ? "border-red-500/50" : "border-[var(--border)]"
            } ${className}`}
            {...props}
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setVisible((v) => !v)}
            disabled={disabled}
            aria-label={visible ? t("hidePassword") : t("showPassword")}
            className="absolute inset-y-0 end-0 flex cursor-pointer items-center px-3 text-[var(--text-faint)] transition-colors hover:text-[var(--text-muted)] disabled:cursor-not-allowed disabled:opacity-50"
          >
            {visible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        </div>
        {error && (
          <p id={`${inputId}-error`} className="text-xs text-red-400" role="alert">
            {error}
          </p>
        )}
      </div>
    );
  }
);

PasswordInput.displayName = "PasswordInput";
export default PasswordInput;
