"use client"

import {useEffect} from "react"
import {OtpInputProps} from "../../props"
import styles from "./styles.module.sass"

export const OtpInput = (props: OtpInputProps) => {
  const {type = "number", handleInputChange, inputRefs, otpValues, error, handleKeyDown} = props

  useEffect(() => {
    // Focus on the first OTP input when the component mounts
    if (inputRefs.current && inputRefs.current[0]) inputRefs.current[0].focus()
  }, [inputRefs])

  const onRef = (index: number, ref: HTMLInputElement) => {
    inputRefs.current[index] = ref
  }

  const renderInputNumber = (value: string, index: number) => (
    <input
      key={index}
      id={`otp-input-${index}`}
      type={type}
      className={`${styles.otp_box} semi-bold`}
      inputMode="numeric"
      maxLength={1}
      value={value}
      autoComplete="one-time-code"
      data-error={!!error}
      data-type={type}
      onChange={handleInputChange.bind(null, index)}
      onKeyDown={handleKeyDown.bind(null, index)}
      ref={onRef.bind(null, index)}
    />
  )

  return (
    <section className={`flex-col-center ${styles.otp_container}`}>
      <section className={`${styles.otp_field}`}>{otpValues.map(renderInputNumber)}</section>
      {error && <p className="error-text">{error}</p>}
    </section>
  )
}
