import React, { useRef } from "react"

type OtpInputProps = {
  length?: number
  value?: string
  onChange?: (value: string) => void
}

export default function OtpInput({ length = 6, value = "", onChange }: OtpInputProps) {
  const inputs = useRef<Array<HTMLInputElement | null>>([])

  const handleChange = (val: string, idx: number) => {
    const chars = value.split("")
    chars[idx] = val.replace(/[^0-9]/g, "")
    const newVal = chars.join("")
    onChange?.(newVal)
    if (val && idx < length - 1) inputs.current[idx + 1]?.focus()
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, idx: number) => {
    if (e.key === "Backspace" && !((e.target as HTMLInputElement).value) && idx > 0) {
      inputs.current[idx - 1]?.focus()
    }
  }

  const cells = [] as React.ReactNode[]
  for (let i = 0; i < length; i++) {
    const char = value[i] ?? ""
    cells.push(
      <input
        key={i}
        ref={(el) => {
          inputs.current[i] = el
        }}
        type="text"
        inputMode="numeric"
        maxLength={1}
        value={char}
        onChange={(e) => handleChange(e.target.value, i)}
        onKeyDown={(e) => handleKeyDown(e, i)}
        className="w-14 h-14 mx-1 text-center text-lg font-semibold border-2 border-input rounded-lg bg-background text-foreground transition-all outline-none placeholder:text-muted-foreground focus:border-ring focus:ring-3 focus:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:border-input dark:bg-input/30 dark:focus:ring-ring/30"
      />
    )
  }

  return <div className="flex justify-center gap-1">{cells}</div>
}

export { OtpInput }
