import React, { useState } from 'react';

export interface FloatingInputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'className'> {
  label?: string;
  className?: {
    container?: string;
    label?: string;
    input?: string;
  };
}

/**
 * Componente `FloatingInput` reutilizable con soporte para estilo flotante de Bootstrap.
 *
 * Similar al componente `Input`, pero adaptado al sistema `form-floating` de Bootstrap.
 * Soporta personalización de clases, tipo `password` con visibilidad opcional y accesibilidad.
 */
export default function FloatingInput(props: FloatingInputProps) {
  const { className, label, type, name, id, ...rest } = props;
  const [showPassword, setShowPassword] = useState(false);

  const isPassword = type === 'password';
  const inputType = isPassword && showPassword ? 'text' : type;
  const inputId =
    id ||
    name ||
    (label ? `floating-${label.replace(/\s+/g, '-')}` : undefined);

  const togglePasswordVisibility = () => setShowPassword(!showPassword);

  return (
    <div className={`form-floating bg-white ${className?.container || 'mb-3'}`}>
      <input
        id={inputId}
        name={name}
        type={inputType}
        className={`form-control ${className?.input || ''}`}
        placeholder={label || ''}
        {...rest}
      />
      {label && (
        <label htmlFor={inputId} className={className?.label || ''}>
          {label}
        </label>
      )}

      {/* Botón para mostrar/ocultar contraseña */}
      {isPassword && (
        <button
          type='button'
          className='btn btn-light border position-absolute top-50 end-0 translate-middle-y me-2'
          style={{ zIndex: 5 }}
          onClick={togglePasswordVisibility}
          aria-label={
            showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'
          }
          title={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
        >
          <i className={`bi ${showPassword ? 'bi-eye-slash' : 'bi-eye'}`}></i>
        </button>
      )}
    </div>
  );
}
