import React, { useMemo, useRef, useState } from "react";

export default function OtpResetStoreOnly({
  length = 6,
  secondsLeft = 0,
  canResend = false,
  onResend,
  formatTime = (s) => {
    const m = Math.floor(s / 60);
    const r = s % 60;
    return `${m}:${String(r).padStart(2, "0")}`;
  },
  label = "کد تایید",
  onCodeChange, // (codeString)=>void
  errorText,
}) {
  const [vals, setVals] = useState(() => Array.from({ length }, () => ""));
  const inputsRef = useRef([]);

  const codeValue = useMemo(() => vals.join(""), [vals]);

  const focusIndex = (i) => {
    const el = inputsRef.current?.[i];
    if (el) {
      el.focus();
      el.select?.();
    }
  };

  const setAt = (i, v) => {
    setVals((prev) => {
      const next = [...prev];
      next[i] = v;
      return next;
    });
  };

  const emit = (nextVals) => {
    const code = nextVals.join("");
    onCodeChange?.(code); // ✅ فقط نگه‌داری
  };

  const handleChange = (i, e) => {
    const raw = e.target.value ?? "";
    const digits = String(raw).replace(/\D/g, "");

    if (!digits) {
      setVals((prev) => {
        const next = [...prev];
        next[i] = "";
        emit(next);
        return next;
      });
      return;
    }

    const chunk = digits.slice(0, length - i).split("");
    setVals((prev) => {
      const next = [...prev];
      for (let k = 0; k < chunk.length; k++) next[i + k] = chunk[k];
      emit(next);
      return next;
    });

    focusIndex(Math.min(i + chunk.length, length - 1));
  };

  const handleKeyDown = (i, e) => {
    if (e.key === "Backspace") {
      if (vals[i]) {
        setVals((prev) => {
          const next = [...prev];
          next[i] = "";
          emit(next);
          return next;
        });
        return;
      }
      if (i > 0) focusIndex(i - 1);
      return;
    }

    if (e.key === "ArrowLeft" && i > 0) focusIndex(i - 1);
    if (e.key === "ArrowRight" && i < length - 1) focusIndex(i + 1);
  };

  const handlePaste = (e) => {
    const text = e.clipboardData?.getData("text") ?? "";
    const digits = String(text).replace(/\D/g, "");
    if (!digits) return;

    e.preventDefault();

    const chunk = digits.slice(0, length).split("");
    setVals((prev) => {
      const next = [...prev];
      for (let i = 0; i < length; i++) next[i] = chunk[i] || "";
      emit(next);
      return next;
    });

    const last = Math.min(chunk.length, length) - 1;
    if (last >= 0) focusIndex(last);
  };

  return (
    <div className="mt-6">
      <div className="text-white mb-2 font-medium">{label}</div>

      <div className="flex items-center gap-2 justify-between" dir="ltr" onPaste={handlePaste}>
        {Array.from({ length }).map((_, i) => (
          <input
            key={i}
            ref={(el) => (inputsRef.current[i] = el)}
            inputMode="numeric"
            autoComplete="one-time-code"
            className="h-14 w-12 rounded-md text-center text-white bg-[#A1E3F919] outline-0 focus:outline-0 ring-0 focus:ring-2 focus:ring-white/30"
            value={vals[i]}
            onChange={(e) => handleChange(i, e)}
            onKeyDown={(e) => handleKeyDown(i, e)}
          />
        ))}
      </div>

      {errorText ? <div className="text-red-600 font-bold text-sm mt-2">{errorText}</div> : null}

      <div className="mt-3 text-sm text-white flex items-center justify-between">
        <span>
          {secondsLeft > 0
            ? `ارسال مجدد کد تا ${formatTime(secondsLeft)} دیگر غیرفعال است`
            : "می‌توانید کد را دوباره ارسال کنید."}
        </span>

        <button
          type="button"
          onClick={onResend}
          disabled={!canResend}
          className={`underline ${canResend ? "cursor-pointer" : "cursor-not-allowed opacity-50"}`}
        >
          ارسال مجدد کد
        </button>
      </div>
    </div>
  );
}
