'use client';

import { Input } from '@/components/ui/input';
import { cn } from '@/lib/cn';
import { forwardRef, useEffect, useRef } from 'react';

interface OTPInputProps {
    value: string;
    onChange: (value: string) => void;
    length?: number;
    className?: string;
}

export const OTPInput = forwardRef<HTMLDivElement, OTPInputProps>(
    ({ value, onChange, length = 6, className }, ref) => {
        const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

        useEffect(() => {
            inputRefs.current = inputRefs.current.slice(0, length);
        }, [length]);

        const handleChange = (index: number, val: string) => {
            if (val.length > 1) {
                val = val.slice(-1);
            }

            if (!/^\d*$/.test(val)) {
                return;
            }

            const newValue = value.split('');
            newValue[index] = val;
            const newOtpValue = newValue.join('').slice(0, length);
            
            onChange(newOtpValue);

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

        const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
            if (e.key === 'Backspace' && !value[index] && index > 0) {
                inputRefs.current[index - 1]?.focus();
            } else if (e.key === 'ArrowLeft' && index > 0) {
                inputRefs.current[index - 1]?.focus();
            } else if (e.key === 'ArrowRight' && index < length - 1) {
                inputRefs.current[index + 1]?.focus();
            }
        };

        const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
            e.preventDefault();
            const pastedData = e.clipboardData.getData('text').slice(0, length);
            
            if (/^\d+$/.test(pastedData)) {
                onChange(pastedData);
                const focusIndex = Math.min(pastedData.length, length - 1);
                inputRefs.current[focusIndex]?.focus();
            }
        };

        return (
            <div ref={ref} dir="ltr" className={cn("flex gap-2 justify-center", className)}>
                {Array.from({ length }, (_, index) => (
                    <Input
                        key={index}
                        ref={(el) => {
                            inputRefs.current[index] = el;
                        }}
                        type="text"
                        inputMode="numeric"
                        pattern="[0-9]*"
                        maxLength={1}
                        value={value[index] || ''}
                        onChange={(e) => handleChange(index, e.target.value)}
                        onKeyDown={(e) => handleKeyDown(index, e)}
                        onPaste={handlePaste}
                        className="w-12 h-12 text-center text-lg font-semibold border-gray-300 focus:ring-gray-300 focus:ring-1"
                    />
                ))}
            </div>
        );
    }
);

OTPInput.displayName = 'OTPInput';
