import React, { useEffect, useRef } from 'react';
import { Input } from 'antd';
import type { InputRef } from 'antd';

interface PinBoxesProps {
  value: string;
  onChange: (value: string) => void;
  onEnter?: () => void;
  length?: number;
  autoFocus?: boolean;
  disabled?: boolean;
}

// Row of single-digit boxes (antd 5.9 has no Input.OTP). Supports typing,
// paste, backspace and arrow-key navigation.
export default function PinBoxes({
  value,
  onChange,
  onEnter,
  length = 6,
  autoFocus = true,
  disabled = false,
}: PinBoxesProps) {
  const inputRefs = useRef<(InputRef | null)[]>([]);
  const digits = Array.from({ length }, (_, i) => value[i] || '');

  useEffect(() => {
    if (autoFocus) setTimeout(() => inputRefs.current[0]?.focus(), 100);
  }, [autoFocus]);

  const focusBox = (index: number) => {
    inputRefs.current[Math.max(0, Math.min(length - 1, index))]?.focus();
  };

  const update = (next: string[]) => onChange(next.join('').slice(0, length));

  const handleChange = (index: number, raw: string) => {
    const cleaned = raw.replace(/\D/g, '');
    const next = [...digits];
    if (!cleaned) {
      next[index] = '';
      update(next);
      return;
    }
    // Typing (or pasting) fills this box and flows into the following ones
    cleaned
      .slice(0, length - index)
      .split('')
      .forEach((ch, i) => {
        next[index + i] = ch;
      });
    update(next);
    focusBox(index + cleaned.length);
  };

  const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !digits[index]) {
      e.preventDefault();
      const next = [...digits];
      next[index - 1] = '';
      update(next);
      focusBox(index - 1);
    } else if (e.key === 'ArrowLeft') {
      focusBox(index - 1);
    } else if (e.key === 'ArrowRight') {
      focusBox(index + 1);
    } else if (e.key === 'Enter' && value.length === length) {
      onEnter?.();
    }
  };

  return (
    <div style={{ display: 'flex', gap: 10 }}>
      {digits.map((digit, index) => (
        <Input
          key={index}
          ref={(el) => {
            inputRefs.current[index] = el;
          }}
          value={digit}
          inputMode="numeric"
          autoComplete="off"
          disabled={disabled}
          onChange={(e) => handleChange(index, e.target.value)}
          onKeyDown={(e) => handleKeyDown(index, e)}
          onFocus={(e) => e.target.select()}
          style={{ width: 48, height: 52, textAlign: 'center', fontSize: 22, fontWeight: 600 }}
        />
      ))}
    </div>
  );
}
