import React, { useRef } from 'react';

interface OtpInputSlotsProps {
  value: string[];
  onChange: (index: number, val: string) => void;
  onPaste: (e: React.ClipboardEvent<HTMLInputElement>) => void;
  disabled?: boolean;
}

const OtpInputSlots: React.FC<OtpInputSlotsProps> = ({
  value,
  onChange,
  onPaste,
  disabled = false,
}) => {
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  const handleKeyDown = (
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (e.key === 'Backspace' && value[index] === '') {
      if (index > 0) {
        inputRefs.current[index - 1]?.focus();
      }
    }
  };

  const handleInput = (
    index: number,
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const val = e.target.value.replace(/[^0-9]/g, '');
    const lastChar = val.slice(-1);

    onChange(index, lastChar);

    if (lastChar && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }
  };

  return (
    <div
      className="otp-input-row"
      style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}
    >
      {[0, 1, 2, 3, 4, 5].map((index) => (
        <input
          key={index}
          ref={(el) => {
            inputRefs.current[index] = el;
          }}
          type="text"
          inputMode="numeric"
          pattern="[0-9]*"
          maxLength={1}
          value={value[index] || ''}
          onChange={(e) => handleInput(index, e)}
          onKeyDown={(e) => handleKeyDown(index, e)}
          onPaste={onPaste}
          disabled={disabled}
          style={{
            width: '44px',
            height: '56px',
            textAlign: 'center',
            fontSize: '24px',
            fontWeight: '700',
            color: value[index] ? '#6d28d9' : '#111827',
            backgroundColor: value[index] ? 'rgba(109,40,217,0.08)' : '#fafafa',
            border: 'none',
            borderRadius: '12px',
            outline: 'none',
          }}
          className="otp-slot"
        />
      ))}
    </div>
  );
};

export default OtpInputSlots;
