/**
 * Input Component
 * Pure Tailwind CSS - Clean form inputs
 */

import { forwardRef } from 'react';

const Input = forwardRef(function Input({
  label,
  name,
  type = 'text',
  placeholder,
  value,
  onChange,
  onBlur,
  error,
  disabled = false,
  required = false,
  leftIcon,
  rightIcon,
  helperText,
  className = '',
  ...props
}, ref) {
  const inputId = name || `input-${Math.random().toString(36).substr(2, 9)}`;

  // Handle number input normalization (remove leading zeros, except for phone numbers which use type="text")
  const handleBlur = (e) => {
    if (type === 'number' && e.target.value !== '' && e.target.value !== null && e.target.value !== undefined) {
      const numValue = parseFloat(e.target.value);
      if (!isNaN(numValue)) {
        // Normalize the value by parsing as number (strips leading zeros)
        // Use the input element directly to update the displayed value
        e.target.value = numValue.toString();
        // Create a new event to trigger onChange with normalized value
        const normalizedEvent = {
          ...e,
          target: e.target,
          currentTarget: e.currentTarget,
        };
        // Trigger onChange with normalized value
        if (onChange) {
          onChange(normalizedEvent);
        }
      }
    }
    // Call original onBlur handler
    if (onBlur) {
      onBlur(e);
    }
  };

  const inputBaseStyles = [
    'w-full px-4 py-2.5',
    'bg-white border rounded-lg',
    'text-gray-900 placeholder:text-gray-400',
    'focus:outline-none focus:ring-2 focus:ring-offset-0',
    'transition-all duration-200',
    'disabled:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50',
    'dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100 dark:placeholder:text-gray-500',
  ];

  if (leftIcon) inputBaseStyles.push('pl-10');
  if (rightIcon) inputBaseStyles.push('pr-10');

  if (error) {
    inputBaseStyles.push(
      'border-red-500 focus:ring-red-500 focus:border-red-500',
      'dark:border-red-600 dark:focus:ring-red-600'
    );
  } else {
    inputBaseStyles.push(
      'border-gray-300 focus:ring-blue-500 focus:border-blue-500',
      'hover:border-gray-400',
      'dark:border-gray-600 dark:hover:border-gray-500'
    );
  }

  return (
    <div className={`w-full ${className}`}>
      {label && (
        <label
          htmlFor={inputId}
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {label}
          {required && (
            <span className="text-red-500 dark:text-red-400 ml-1">*</span>
          )}
        </label>
      )}
      <div className="relative">
        {leftIcon && (
          <div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none">
            {leftIcon}
          </div>
        )}
        <input
          ref={ref}
          id={inputId}
          name={name}
          type={type}
          placeholder={placeholder}
          value={value}
          onChange={onChange}
          onBlur={handleBlur}
          disabled={disabled}
          required={required}
          className={inputBaseStyles.join(' ')}
          {...props}
        />
        {rightIcon && (
          <div className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none">
            {rightIcon}
          </div>
        )}
      </div>
      {error && (
        <p className="mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1">
          <svg
            className="w-4 h-4"
            fill="currentColor"
            viewBox="0 0 20 20"
          >
            <path
              fillRule="evenodd"
              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
              clipRule="evenodd"
            />
          </svg>
          {error}
        </p>
      )}
      {helperText && !error && (
        <p className="mt-1.5 text-sm text-gray-500 dark:text-gray-400">
          {helperText}
        </p>
      )}
    </div>
  );
});

Input.displayName = 'Input';

export default Input;
