import { InputHTMLAttributes, forwardRef } from 'react';
import { Trash2 } from 'lucide-react';

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  label?: string;
  error?: string;
  onClear?: () => void;
}

const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ className = '', label, error, id, onClear, ...props }, ref) => {
    const inputId = id || props.name;
    const isDateType = props.type === 'date';
    const hasValue = props.value !== undefined && props.value !== null && props.value !== '';
    const showClearButton = isDateType && onClear && hasValue;

    return (
      <div className="w-full">
        {label && (
          <label htmlFor={inputId} className="block text-sm font-medium text-gray-700 mb-1">
            {label}
          </label>
        )}
        <div className={showClearButton ? 'flex gap-2' : ''}>
          <input
            ref={ref}
            id={inputId}
            className={`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
              error ? 'border-red-500' : 'border-gray-300'
            } ${className}`}
            {...props}
          />
          {showClearButton && (
            <button
              type="button"
              onClick={onClear}
              className="px-3 py-2 text-gray-400 hover:text-red-500 hover:bg-red-50 border border-gray-300 rounded-lg transition-colors"
              title="Datum löschen"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          )}
        </div>
        {error && <p className="mt-1 text-sm text-red-600">{error}</p>}
      </div>
    );
  }
);

Input.displayName = 'Input';

export default Input;
