"use client";

import { useRef, useState } from "react";

export default function OtpInput({
  error,
  label,
  name,
}: {
  error?: string[];
  label: string;
  name: string;
}) {
  const [digits, setDigits] = useState(["", "", "", "", "", ""]);
  const refs = useRef<Array<HTMLInputElement | null>>([]);
  const value = digits.join("");

  function distributeDigits(startIndex: number, rawValue: string) {
    const incoming = rawValue.replace(/\D/g, "").slice(0, 6 - startIndex);
    if (!incoming) return;
    const next = [...digits];
    incoming.split("").forEach((digit, offset) => {
      next[startIndex + offset] = digit;
    });
    setDigits(next);
    refs.current[Math.min(startIndex + incoming.length, 5)]?.focus();
  }

  return (
    <fieldset className="sm:col-span-2">
      <legend className="text-[12px] font-bold text-[#34405d]">{label}</legend>
      <input type="hidden" name={name} value={value} />
      <div className="mt-2 grid max-w-[360px] grid-cols-6 gap-2">
        {digits.map((digit, index) => (
          <input
            key={index}
            ref={(element) => {
              refs.current[index] = element;
            }}
            suppressHydrationWarning
            aria-label={`${label} digit ${index + 1}`}
            autoComplete={index === 0 ? "one-time-code" : "off"}
            className="h-12 min-w-0 rounded-xl border border-[#dce3f1] bg-white text-center text-lg font-extrabold text-[#253052] outline-none transition focus:border-[#6b72f2] focus:ring-3 focus:ring-[#e9eaff]"
            inputMode="numeric"
            maxLength={1}
            pattern="[0-9]"
            type="text"
            value={digit}
            onChange={(event) => {
              const incoming = event.target.value.replace(/\D/g, "");
              if (incoming.length > 1) {
                distributeDigits(index, incoming);
                return;
              }
              const next = [...digits];
              next[index] = incoming;
              setDigits(next);
              if (incoming) refs.current[index + 1]?.focus();
            }}
            onKeyDown={(event) => {
              if (event.key === "Backspace" && !digits[index] && index > 0) {
                refs.current[index - 1]?.focus();
              }
              if (event.key === "ArrowLeft" && index > 0) refs.current[index - 1]?.focus();
              if (event.key === "ArrowRight" && index < 5) refs.current[index + 1]?.focus();
            }}
            onPaste={(event) => {
              event.preventDefault();
              distributeDigits(index, event.clipboardData.getData("text"));
            }}
          />
        ))}
      </div>
      {error?.[0] ? <span className="mt-1 block text-[11px] text-rose-600">{error[0]}</span> : null}
    </fieldset>
  );
}
