import React from 'react';
import { cn } from '@/lib/utils';

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

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, type, label, error, onInvalid, id, ...props }, ref) => {
    // Generate a unique id for accessibility if not provided
    const inputId = id || (label ? label.toLowerCase().replace(/\s+/g, '-') : undefined);

    // Default English validation message
    const handleInvalid = (e: React.InvalidEvent<HTMLInputElement>) => {
      e.target.setCustomValidity('Please fill out this field.');
      if (onInvalid) onInvalid(e);
    };

    const handleInput = (e: React.FormEvent<HTMLInputElement>) => {
      e.currentTarget.setCustomValidity('');
    };

    return (
      <div className="space-y-1">
        {label && (
          <label htmlFor={inputId} className="block text-sm font-medium text-gray-700">
            {label}
          </label>
        )}
        <input
          id={inputId}
          type={type}
          className={cn(
            'flex h-10 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
            error && 'border-red-500 focus-visible:ring-red-500',
            className
          )}
          ref={ref}
          onInvalid={handleInvalid}
          onInput={handleInput}
          {...props}
        />
        {error && (
          <p className="text-sm text-red-600">{error}</p>
        )}
      </div>
    );
  }
);

Input.displayName = 'Input';