/**
 * Reusable OTP Input Component
 * Supports copy-paste and proper validation
 */

import { useRef, useEffect } from "react";

interface OTPInputProps {
  value: string;
  onChange: (value: string) => void;
  error?: string;
  disabled?: boolean;
}

export default function OTPInput({ value, onChange, error, disabled }: OTPInputProps) {
  const inputsRef = useRef<(HTMLInputElement | null)[]>([]);
  const otpArray = value.split("").slice(0, 4);
  const otp = [...otpArray, "", "", "", ""].slice(0, 4);

  useEffect(() => {
    // Auto-focus first empty input
    const firstEmptyIndex = otp.findIndex((digit) => !digit);
    if (firstEmptyIndex !== -1 && inputsRef.current[firstEmptyIndex]) {
      inputsRef.current[firstEmptyIndex]?.focus();
    }
  }, [otp]);

  const handleChange = (inputValue: string, index: number) => {
    if (!/^\d?$/.test(inputValue)) return;

    const newOtp = [...otp];
    newOtp[index] = inputValue;
    const otpString = newOtp.join("").slice(0, 4);
    onChange(otpString);

    // Auto-focus next input
    if (inputValue && index < 3 && inputsRef.current[index + 1]) {
      inputsRef.current[index + 1]?.focus();
    }
  };

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

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const paste = e.clipboardData.getData("text").trim();

    if (!/^\d+$/.test(paste)) return;

    const digits = paste.split("").slice(0, 4);
    const newOtp = ["", "", "", ""];
    digits.forEach((d, i) => {
      newOtp[i] = d;
    });

    onChange(newOtp.join(""));

    // Focus last filled input
    const lastIndex = Math.min(digits.length - 1, 3);
    if (inputsRef.current[lastIndex]) {
      inputsRef.current[lastIndex]?.focus();
    }
  };

  return (
    <>
      <div className="row g-2">
        {[0, 1, 2, 3].map((i) => (
          <div className="col-3" key={i}>
            <input
              ref={(el) => {
                inputsRef.current[i] = el;
              }}
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={1}
              className={`form-control rounded-2 border otp-field text-center ${
                error ? "is-invalid" : ""
              }`}
              value={otp[i]}
              onChange={(e) => handleChange(e.target.value, i)}
              onKeyDown={(e) => handleKeyDown(e, i)}
              onPaste={handlePaste}
              disabled={disabled}
            />
          </div>
        ))}
      </div>
      {error && <div className="invalid-feedback d-block mt-2">{error}</div>}
    </>
  );
}
