'use client';

import { CSSProperties, InputHTMLAttributes, ReactNode, forwardRef } from 'react';
import { cn } from '@/utils/helpers';
import styles from './Input.module.scss';

export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'prefix'> {
  size?: 'sm' | 'md' | 'lg';
  prefix?: ReactNode;
  suffix?: ReactNode;
  error?: string;
  label?: string;
  helperText?: string;
  wrapperStyle?: CSSProperties;
}

export const Input = forwardRef<HTMLInputElement, InputProps>(
  (
    {
      size = 'md',
      prefix,
      suffix,
      error,
      label,
      helperText,
      disabled,
      className,
      id,
      style,
      wrapperStyle,
      ...props
    },
    ref
  ) => {
    const inputId = id || `input-${Math.random().toString(36).substring(7)}`;

    return (
      <div className={cn(styles.inputWrapper, className)} style={wrapperStyle || style}>
        {label && (
          <label htmlFor={inputId} className={styles.inputWrapper__label}>
            {label}
          </label>
        )}
        <div
          className={cn(
            styles.input,
            styles[`input--${size}`],
            error && styles['input--error'],
            disabled && styles['input--disabled']
          )}
        >
          {prefix && <span className={styles.input__prefix}>{prefix}</span>}
          <input
            ref={ref}
            id={inputId}
            className={styles.input__field}
            disabled={disabled}
            {...props}
          />
          {suffix && <span className={styles.input__suffix}>{suffix}</span>}
        </div>
        {(error || helperText) && (
          <span className={cn(styles.inputWrapper__helper, error && styles['inputWrapper__helper--error'])}>
            {error || helperText}
          </span>
        )}
      </div>
    );
  }
);

Input.displayName = 'Input';
