import React, { useState, useRef, useEffect } from "react";

const OTPInput: React.FC<{
  length?: number;
  onComplete: (otp: string) => void;
  code: string | number;
}> = ({ length = 4, onComplete, code }) => {
  const [otpValues, setOtpValues] = useState<string[]>(Array(length).fill(""));
  const inputsRef = useRef<(HTMLInputElement | null)[]>([]);

  // ✅ Pre-fill inputs if code is passed
  useEffect(() => {
    if (code) {
      const codeString = String(code);
      const filled = codeString.split("").slice(0, length);
      const padded = filled.concat(Array(length - filled.length).fill(""));
      setOtpValues(padded);
      if (filled.length === length) {
        onComplete(filled.join(""));
      }
    }
  }, [code, length, onComplete]);

  // ✅ Focus first input on mount
  useEffect(() => {
    inputsRef.current[0]?.focus();
  }, []);

  const handleChange = (value: string, index: number) => {
    if (/^[0-9]?$/.test(value)) {
      const newOtp = [...otpValues];
      newOtp[index] = value;
      setOtpValues(newOtp);

      if (value && index < length - 1) {
        inputsRef.current[index + 1]?.focus();
      }

      // ✅ Only trigger onComplete when all digits are filled
      if (newOtp.every((digit) => digit !== "")) {
        onComplete(newOtp.join(""));
      }
    }
  };

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

  return (
    <div className="otp-container">
      {otpValues.map((value, index) => (
        <input
          key={index}
          type="text"
          className="otp-input"
          maxLength={1}
          value={value ?? ""}
          onChange={(e) => handleChange(e.target.value, index)}
          onKeyDown={(e) => handleKeyDown(e, index)}
          ref={(el) => (inputsRef.current[index] = el)}
        />
      ))}
    </div>
  );
};

export default OTPInput;
