/* 
  This is the single input otp input component.
  It contains the following components:
  - SingleInput
*/
import React, { memo, useRef, useLayoutEffect } from 'react'
import usePrevious from './hooks/usePrevious'

// Define the props type for the SingleOTPInput component
interface SingleOTPInputProps {
    focus?: boolean;
    autoFocus?: boolean;
    className?: string;
    value?: string;
    onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
    onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
    onPaste?: (e: React.ClipboardEvent<HTMLInputElement>) => void;
    onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
    onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
    type?: string;
    disabled?: boolean;
    style?: React.CSSProperties;
}

export function SingleOTPInputComponent(props: SingleOTPInputProps) {
    const { focus, autoFocus, className, ...rest } = props
    const inputRef = useRef<HTMLInputElement>(null)
    const prevFocus = usePrevious(!!focus)
    // Use the layout effect to focus the input
    useLayoutEffect(() => {
        if (inputRef.current) {
            if (focus && autoFocus) {
                inputRef.current.focus()
            }
            if (focus && autoFocus && focus !== prevFocus) {
                inputRef.current.focus()
                inputRef.current.select()
            }
        }
    }, [autoFocus, focus, prevFocus])

    return <input ref={inputRef} {...rest} aria-label="OTPnumber" />
}

const SingleOTPInput = memo(SingleOTPInputComponent)
export default SingleOTPInput
