"use client";

import { useRef, KeyboardEvent, ClipboardEvent } from "react";

interface OtpInputProps {
  value: string;
  onChange: (val: string) => void;
  error?: string;
}

export function OtpInput({ value, onChange, error }: OtpInputProps) {
  const inputs = useRef<(HTMLInputElement | null)[]>([]);
  const digits = value.padEnd(6, "").split("").slice(0, 6);

  const update = (idx: number, char: string) => {
    const next = digits.slice();
    next[idx] = char.replace(/\D/, "");
    onChange(next.join("").trimEnd());
    if (char && idx < 5) inputs.current[idx + 1]?.focus();
  };

  const handleKey = (idx: number, e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Backspace") {
      if (!digits[idx] && idx > 0) {
        update(idx - 1, "");
        inputs.current[idx - 1]?.focus();
      } else {
        update(idx, "");
      }
    }
  };

  const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    onChange(pasted);
    inputs.current[Math.min(pasted.length, 5)]?.focus();
  };

  return (
    <div>
      <div className="flex gap-2 justify-center">
        {Array.from({ length: 6 }).map((_, i) => (
          <input
            key={i}
            ref={(el) => { inputs.current[i] = el; }}
            type="text"
            inputMode="numeric"
            maxLength={1}
            value={digits[i] || ""}
            onChange={(e) => update(i, e.target.value.slice(-1))}
            onKeyDown={(e) => handleKey(i, e)}
            onPaste={handlePaste}
            onFocus={(e) => e.target.select()}
            className="w-11 h-13 text-center text-lg font-bold rounded-xl transition-all duration-150 outline-none"
            style={{
              height: "52px",
              background: "var(--deep)",
              border: `1.5px solid ${digits[i] ? "var(--accent)" : error ? "#ef4444" : "var(--border)"}`,
              color: "var(--text-primary)",
              caretColor: "var(--accent)",
            }}
          />
        ))}
      </div>
      {error && (
        <p className="text-xs mt-2 text-center" style={{ color: "#ef4444" }}>
          {error}
        </p>
      )}
    </div>
  );
}
