'use client';
import { useState, useRef } from 'react';
import { Each, Show } from '../../00-base';
import { Paragraph } from '../Paragraph';
import clsx from 'clsx';
/**
 * OtpInput component for rendering a one-time password input field with multiple digit boxes.
 *
 * @component
 * @example
 * // Example usage of OtpInput component
 * <OtpInput
 *   label="Enter verification code"
 *   length={6}
 *   disabled={false}
 *   handleSubmit={(otp) => console.log('OTP submitted:', otp)}
 *   error="Invalid code"
 * />
 *
 * @param {Object} props - The properties of the OtpInput component.
 * @param {string} props.label - The label text displayed above the input fields.
 * @param {number} [props.length=4] - The number of input boxes to display. Default is 4.
 * @param {boolean} [props.disabled=false] - Whether the input fields are disabled.
 * @param {string} [props.labelStyle] - Additional CSS classes for the label.
 * @param {string} [props.error] - Error message to be displayed below the input fields.
 * @param {(otp: string) => void} props.handleSubmit - Callback function called when the OTP is complete (all boxes filled).
 * @param {React.HTMLAttributes<HTMLDivElement>} [props.restProps] - Additional HTML attributes for the container div.
 * @required props.label, props.handleSubmit
 *
 * @returns {ReactNode} The rendered OtpInput component.
 */
export function OtpInput({ length = 4, disabled = false, label, labelStyle, error, handleSubmit, ...restProps }) {
    const [otp, setOtp] = useState(Array.from({ length }, () => ''));
    const inputRefs = useRef([]);
    const onSubmit = (newCode) => setTimeout(() => handleSubmit(newCode.join('')), 100);
    const handleInputChange = (index, value) => {
        if (value && !/^\d$/.test(value))
            return;
        const newCode = [...otp];
        newCode[index] = value;
        setOtp(newCode);
        if (value && index < otp.length - 1) {
            inputRefs.current[index + 1]?.focus();
        }
        if (newCode.filter((item) => item).join('').length === length) {
            onSubmit(newCode);
        }
    };
    const handleKeyDown = (index, e) => {
        if (e.key === 'Backspace' && !otp[index] && index > 0) {
            inputRefs.current[index - 1]?.focus();
        }
        if (e.key === 'Backspace' &&
            otp.filter((item) => item).join('').length === length) {
            onSubmit(otp.slice(0, -1));
        }
    };
    const handlePaste = (e) => {
        e.preventDefault();
        const pastedData = e.clipboardData.getData('text').slice(0, 6);
        if (!/^\d+$/.test(pastedData))
            return;
        const newCode = [...otp];
        pastedData.split('').forEach((char, index) => {
            if (index < length) {
                newCode[index] = char;
            }
        });
        inputRefs.current[length - 1]?.focus();
        setOtp(newCode);
        onSubmit(newCode);
    };
    return (<div {...restProps} className={clsx('w-full', restProps.className)}>
      <Paragraph size="body-1" className={clsx('text-lavender pb-4', labelStyle)}>
        {label}
      </Paragraph>

      <div className="flex items-center gap-x-2" onPaste={handlePaste}>
        <Each of={Array.from({ length })} render={(_, index) => (<input ref={(me) => {
                if (me) {
                    inputRefs.current[index] = me;
                }
            }} name={`otp-${index}`} key={`OtpInput-${index}`} value={otp[index]} onChange={(e) => handleInputChange(index, e.target.value)} onKeyDown={(e) => handleKeyDown(index, e)} type="text" maxLength={1} className={clsx('disabled:border-gray-3 disabled:text-gray-3 size-10 rounded-lg border bg-transparent text-center text-sm font-normal text-black outline-0 transition-all focus:text-black', error ? 'border-error' : 'border-lavender')} disabled={disabled}/>)}/>
      </div>

      <Show>
        <Show.When isTrue={!!error}>
          <Paragraph size="body-2" className="text-error pt-2">
            {error}
          </Paragraph>
        </Show.When>
      </Show>
    </div>);
}
//# sourceMappingURL=OtpInput.jsx.map