import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp';
import type { SlotProps } from 'input-otp';
import { cn } from '@/lib/utils';

function OtpSlot({ char, isActive, hasFakeCaret }: SlotProps) {
    return (
        <div
            className={cn(
                'relative flex aspect-square w-full max-w-16 items-center justify-center rounded-xl border text-2xl transition-colors sm:text-3xl',
                char
                    ? 'border-gold bg-[#f6efe2] text-navy'
                    : 'border-navy/15 dark:border-white/15',
                isActive && 'border-gold ring-2 ring-gold/30',
            )}
        >
            {char}
            {hasFakeCaret && (
                <span className="h-7 w-px animate-caret-blink bg-current" />
            )}
        </div>
    );
}

type Props = {
    value: string;
    onChange: (value: string) => void;
    length: number;
    name?: string;
};

export default function OtpCodeInput({
    value,
    onChange,
    length,
    name = 'code',
}: Props) {
    return (
        <OTPInput
            name={name}
            value={value}
            onChange={onChange}
            maxLength={length}
            pattern={REGEXP_ONLY_DIGITS}
            autoFocus
            containerClassName="grid grid-cols-6 gap-2 sm:gap-3"
            render={({ slots }) => (
                <>
                    {slots.map((slot, index) => (
                        <OtpSlot key={index} {...slot} />
                    ))}
                </>
            )}
        />
    );
}
