'use client';

import { useRef, useEffect } from 'react';

interface OtpDigitInputProps {
  length?: number;
  value: string;
  onChange: (value: string) => void;
  disabled?: boolean;
  invalid?: boolean;
}

/**
 * Fresh 6-digit implementation, not a reuse of
 * `components/auth/shared/OTPInput.tsx` — that one is hardcoded to 4 digits
 * and Bootstrap classes for the ported Personal-mode signup flow; this needs
 * 6 digits. Sizing/colors match the design prototype's `.emp-otp` exactly
 * (54px boxes, 10px gap desktop; 48px boxes, 6px gap at <576px).
 */
export default function OtpDigitInput({ length = 6, value, onChange, disabled, invalid }: OtpDigitInputProps) {
  const inputsRef = useRef<(HTMLInputElement | null)[]>([]);
  const digits = [...value.split('').slice(0, length), ...Array(length).fill('')].slice(0, length);

  useEffect(() => {
    const firstEmpty = digits.findIndex((d) => !d);
    inputsRef.current[firstEmpty === -1 ? 0 : firstEmpty]?.focus();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleChange = (input: string, index: number) => {
    if (!/^\d?$/.test(input)) return;
    const next = [...digits];
    next[index] = input;
    onChange(next.join(''));
    if (input && index < length - 1) inputsRef.current[index + 1]?.focus();
  };

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

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData('text').trim();
    if (!/^\d+$/.test(pasted)) return;
    const pastedDigits = pasted.split('').slice(0, length);
    onChange(pastedDigits.join(''));
    const lastIndex = Math.min(pastedDigits.length - 1, length - 1);
    inputsRef.current[lastIndex]?.focus();
  };

  return (
    <div className="grid grid-cols-6 gap-1.5 sm:gap-2.5" role="group" aria-label="One-time password">
      {digits.map((digit, i) => (
        <input
          key={i}
          ref={(el) => {
            inputsRef.current[i] = el;
          }}
          type="text"
          inputMode="numeric"
          maxLength={1}
          aria-label={`Digit ${i + 1}`}
          autoComplete={i === 0 ? 'one-time-code' : 'off'}
          value={digit}
          disabled={disabled}
          onChange={(e) => handleChange(e.target.value, i)}
          onKeyDown={(e) => handleKeyDown(e, i)}
          onPaste={handlePaste}
          className={`h-12 w-full rounded-[10px] border p-0 text-center text-xl font-bold outline-none transition-colors sm:h-[54px] sm:rounded-xl sm:text-[22px] ${
            invalid
              ? 'border-[var(--fra-rejected)]'
              : digit
                ? 'border-[var(--fra-navy-2)] bg-[var(--fra-surface-2)]'
                : 'border-[var(--fra-border-strong)] bg-[var(--fra-surface)]'
          } text-[var(--fra-heading)] focus:border-[var(--fra-navy-2)] focus:shadow-[0_0_0_3px_rgba(27,77,97,0.15)] disabled:opacity-50`}
        />
      ))}
    </div>
  );
}
