'use client';

import { Input } from '@admin/components/ui/input';
import { cn } from '@admin/utils/common';
import { Controller, useFormContext } from 'react-hook-form';

interface OTPFieldProps {
    name: string;
    disabled?: boolean;
    className?: string;
    length?: number;
}

export const OTPField = ({ name, disabled, className, length }: OTPFieldProps) => {
    const { control } = useFormContext();

    return (
        <Controller
            control={control}
            name={name}
            render={({ field }) => {
                const fieldLength = length || 6;
                const values = field.value ? field.value.split('') : Array(fieldLength).fill('');

                const handleChange = (index: number, value: string) => {
                    if (value.length > 1) return;
                    const newValues = [...values];
                    newValues[index] = value;
                    field.onChange(newValues.join(''));

                    // Auto-focus next input
                    if (value && index < fieldLength - 1) {
                        const nextInput = document.getElementById(`${name}-${index + 1}`);
                        nextInput?.focus();
                    }
                };

                const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
                    if (e.key === 'Backspace' && !values[index] && index > 0) {
                        const prevInput = document.getElementById(`${name}-${index - 1}`);
                        prevInput?.focus();
                    }
                };

                return (
                    <div className={cn('flex gap-2', className)}>
                        {Array.from({ length: fieldLength }, (_, index) => (
                            <Input
                                key={index}
                                id={`${name}-${index}`}
                                type="text"
                                maxLength={1}
                                value={values[index] || ''}
                                onChange={(e) => handleChange(index, e.target.value)}
                                onKeyDown={(e) => handleKeyDown(index, e)}
                                disabled={disabled}
                                className="h-12 w-12 text-center text-lg font-semibold"
                            />
                        ))}
                    </div>
                );
            }}
        />
    );
};
