import React from 'react';
import { Check, X } from 'lucide-react';

export type ValidationStatus = 'idle' | 'valid' | 'invalid';

export interface ValidatedInputProps extends Omit<React.ComponentProps<'input'>, 'aria-invalid'> {
  label?: string;
  validationStatus?: ValidationStatus;
  errorMessage?: string;
  helperText?: string;
  showValidationIcon?: boolean;
  fullWidth?: boolean;
}

const statusStyles: Record<
  ValidationStatus,
  { border: string; focus: string; icon: React.ReactNode | null; ariaInvalid: boolean }
> = {
  idle: {
    border: 'border-term-border',
    focus: 'focus:border-info',
    icon: null,
    ariaInvalid: false,
  },
  valid: {
    border: 'border-[var(--term-status-success-border)]',
    focus: 'focus:border-positive',
    icon: <Check className="h-4 w-4 text-positive" />,
    ariaInvalid: false,
  },
  invalid: {
    border: 'border-[var(--term-status-error-border)]',
    focus: 'focus:border-negative',
    icon: <X className="h-4 w-4 text-negative" />,
    ariaInvalid: true,
  },
};

export const ValidatedInput: React.FC<ValidatedInputProps> = ({
  label,
  validationStatus = 'idle',
  errorMessage,
  helperText,
  showValidationIcon = true,
  fullWidth = true,
  className = '',
  id,
  ...props
}) => {
  const styles = statusStyles[validationStatus];
  const inputId = id ?? `input-${Math.random().toString(36).substring(2, 9)}`;
  const errorId = `${inputId}-error`;
  const helperId = `${inputId}-helper`;

  const baseClassName =
    'rounded border bg-term-surface px-3 py-2 text-sm font-mono text-term-text outline-none transition-colors';
  const borderClassName = `${styles.border} ${styles.focus}`;
  const widthClassName = fullWidth ? 'w-full' : '';
  const iconWidth = showValidationIcon ? 'pr-10' : '';

  return (
    <label className={`${fullWidth ? 'block' : ''} ${className}`}>
      {label && (
        <span className="mb-2 block text-xs font-mono text-term-text-muted">{label}</span>
      )}
      <div className="relative">
        <input
          id={inputId}
          className={`${baseClassName} ${borderClassName} ${widthClassName} ${iconWidth} ${className}`}
          aria-invalid={styles.ariaInvalid}
          aria-describedby={
            validationStatus === 'invalid' && errorMessage
              ? errorId
              : helperText
                ? helperId
                : undefined
          }
          {...props}
        />
        {showValidationIcon && styles.icon && (
          <span
            className="absolute right-3 top-1/2 -translate-y-1/2"
            aria-hidden="true"
          >
            {styles.icon}
          </span>
        )}
      </div>
      {validationStatus === 'invalid' && errorMessage && (
        <p id={errorId} className="mt-1.5 text-xs font-mono text-negative" role="alert">
          {errorMessage}
        </p>
      )}
      {validationStatus !== 'invalid' && helperText && (
        <p id={helperId} className="mt-1.5 text-xs font-mono text-term-text-muted">
          {helperText}
        </p>
      )}
    </label>
  );
};
