"use client";

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

interface OtpInputProps {
  value: string;
  onChange: (value: string) => void;
  error?: any;
  length?: number;
}

const OtpInput: React.FC<OtpInputProps> = ({
  value,
  onChange,
  error,
  length = 4,
}) => {
  const [digits, setDigits] = useState<string[]>(Array(length).fill(""));
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  // Sync internal digits with incoming value prop
  useEffect(() => {
    const newDigits = value.split("").concat(Array(length).fill("")).slice(0, length);
    setDigits(newDigits);
  }, [value, length]);

  const handleChange = (index: number, val: string) => {
    // Only allow digits
    if (val && !/^\d+$/.test(val)) return;

    const char = val.slice(-1);
    const newDigits = [...digits];
    newDigits[index] = char;
    
    const newValue = newDigits.join("");
    onChange(newValue);

    // Move to next field
    if (char && index < length - 1) {
      inputRefs.current[index + 1]?.focus();
    }
  };

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

  const handlePaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const data = e.clipboardData.getData("text").trim().slice(0, length);
    if (!/^\d+$/.test(data)) return;

    const newDigits = data.split("").concat(Array(length).fill("")).slice(0, length);
    onChange(newDigits.join(""));

    // Focus last filled or next empty
    const nextIndex = Math.min(data.length, length - 1);
    inputRefs.current[nextIndex]?.focus();
  };

  return (
    <div className="flex flex-col items-center space-y-2 w-full max-w-[399px]">
      <div className="flex gap-[16px] justify-center w-full">
        {digits.map((digit, index) => (
          <div
            key={index}
            className={`relative flex items-center justify-center w-[60px] h-[60px] rounded-[10px] border transition-all bg-white ${
              error ? "border-red-500" : "border-brand-border-alt"
            } focus-within:border-blue-light focus-within:border-[1.5px]`}
          >
            <input
              ref={(el) => {
                inputRefs.current[index] = el;
              }}
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={1}
              value={digit}
              onChange={(e) => handleChange(index, e.target.value)}
              onKeyDown={(e) => handleKeyDown(index, e)}
              onPaste={index === 0 ? handlePaste : undefined}
              className="w-full h-full bg-transparent outline-none text-[32px] font-bold text-blue-deep font-sans text-center"
            />
          </div>
        ))}
      </div>
      {error && (
        <p className="text-red-500 text-xs mt-1 font-sans text-center">
          {error.message}
        </p>
      )}
    </div>
  );
};

export default OtpInput;
