'use client'

import React, { useRef } from 'react'
import { Control, Controller } from 'react-hook-form'

interface OTPInputProps {
    name: string
    control: Control<any>
    length?: number
    error?: string
}

export const OTPInput = ({
    name,
    control,
    length = 6,
    error
}: OTPInputProps) => {
    const inputs = useRef<(HTMLInputElement | null)[]>([])

    const focusInput = (index: number) => {
        inputs.current[index]?.focus()
    }

    return (
        <Controller
            name={name}
            control={control}
            render={({ field }) => {
                const value = field.value || ''

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

                    const otpArray = value.split('')
                    otpArray[index] = val
                    const updatedOtp = otpArray.join('').slice(0, length)

                    field.onChange(updatedOtp)

                    if (val && index < length - 1) {
                        focusInput(index + 1)
                    }
                }

                const handleKeyDown = (
                    e: React.KeyboardEvent<HTMLInputElement>,
                    index: number
                ) => {
                    if (e.key === 'Backspace' && !value[index] && index > 0) {
                        focusInput(index - 1)
                    }
                }

                const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
                    const pasted = e.clipboardData.getData('text').slice(0, length)
                    if (!/^\d+$/.test(pasted)) return

                    field.onChange(pasted)
                    focusInput(pasted.length === length ? length - 1 : pasted.length)
                }

                return (
                    <>
                        <div className="flex items-stretch gap-2 md:gap-4 lg:gap-6 mb-2">
                            {Array.from({ length }).map((_, i) => (
                                <input
                                    key={i}
                                    ref={(el) => {
                                        inputs.current[i] = el
                                    }}
                                    type="text"
                                    inputMode="numeric"
                                    maxLength={1}
                                    value={value[i] || ''}
                                    onChange={(e) => handleChange(e.target.value, i)}
                                    onKeyDown={(e) => handleKeyDown(e, i)}
                                    onPaste={handlePaste}
                                    className="w-full border border-grey32 bg-secondary25 px-2 py-2.5 md:py-4 rounded-lg md:rounded-2xl text-base font-normal leading-tight outline-none focus:border-light text-center"
                                />

                            ))}
                        </div>

                        {error && (
                            <p className="text-red-500 text-sm mt-1 text-center">{error}</p>
                        )}
                    </>
                )
            }}
        />
    )
}
