/**
 * OtpInput - 6-digit OTP code input
 *
 * Wrapper around shadcn InputOTP (backed by input-otp library).
 * Provides mobile SMS autofill, paste support, and accessible slot rendering.
 */

"use client";

import { REGEXP_ONLY_DIGITS } from "input-otp";
import { cn } from "@/shared/utils";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";

interface OtpInputProps {
  length?: number | undefined;
  value: string;
  onChange: (value: string) => void;
  onComplete?: ((value: string) => void) | undefined;
  disabled?: boolean | undefined;
  error?: string | undefined;
  autoFocus?: boolean | undefined;
}

export function OtpInput({
  length = 6,
  value,
  onChange,
  onComplete,
  disabled = false,
  error,
  autoFocus = true,
}: OtpInputProps) {
  return (
    <div className="space-y-2">
      <div className="flex justify-center">
        <InputOTP
          maxLength={length}
          value={value}
          onChange={onChange}
          {...(onComplete && { onComplete })}
          disabled={disabled}
          autoFocus={autoFocus}
          pattern={REGEXP_ONLY_DIGITS}
          containerClassName="justify-center"
        >
          <InputOTPGroup>
            {Array.from({ length }, (_, i) => (
              <InputOTPSlot key={i} index={i} className={cn(error && "border-danger")} />
            ))}
          </InputOTPGroup>
        </InputOTP>
      </div>
      {error && (
        <p className="text-sm text-danger text-center" role="alert">
          {error}
        </p>
      )}
    </div>
  );
}
