import { useEffect, useRef, useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Btn } from "@/pages/app/components/ui";
import { StepIndicator } from "@/pages/app/components/bo/BoUI";

/**
 * A single OTP step of a multi-step flow: back arrow + step indicator +
 * 4 code boxes + countdown/resend + confirm button (in the normal flow).
 */
export default function OtpStep({
  title,
  step,
  total,
  hint,
  target,
  confirmLabel,
  errorLabel = "الكود غير صحيح",
  onConfirm,
}: {
  title: string;
  step: number;
  total: number;
  hint: string;
  target: string;
  confirmLabel: string;
  errorLabel?: string;
  onConfirm: () => void;
}) {
  const { goBack } = useApp();
  const [digits, setDigits] = useState(["", "", "", ""]);
  const [seconds, setSeconds] = useState(45);
  const [error, setError] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const refs = useRef<Array<HTMLInputElement | null>>([]);

  useEffect(() => {
    if (seconds <= 0) return;
    const t = setInterval(() => setSeconds((s) => s - 1), 1000);
    return () => clearInterval(t);
  }, [seconds]);

  const setDigit = (idx: number, val: string) => {
    const v = val.replace(/\D/g, "").slice(-1);
    setError(false);
    setDigits((d) => {
      const next = [...d];
      next[idx] = v;
      return next;
    });
    if (v && idx < 3) refs.current[idx + 1]?.focus();
  };

  const filled = digits.every((d) => d !== "");

  const confirm = () => {
    if (!filled) {
      setError(true);
      return;
    }
    setVerifying(true);
    setTimeout(() => {
      setVerifying(false);
      // demo: treat "1234" as wrong to showcase the error state
      if (digits.join("") === "1234") {
        setError(true);
        return;
      }
      onConfirm();
    }, 900);
  };

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title={title} onBack={goBack} />

      <div className="px-5 pt-4">
        <StepIndicator current={step} total={total} />
      </div>

      <div className="flex-1 px-6 pt-7">
        <p className="text-[13.5px] text-foreground-600 leading-relaxed text-center">{hint}</p>
        <p className="text-[15px] font-semibold text-foreground-950 text-center mt-1" dir="ltr">
          {target}
        </p>

        <div className="grid grid-cols-4 gap-3.5 w-full max-w-[288px] mx-auto mt-8" dir="ltr">
          {digits.map((d, i) => (
            <input
              key={i}
              ref={(el) => {
                refs.current[i] = el;
              }}
              value={d}
              onChange={(e) => setDigit(i, e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Backspace" && !digits[i] && i > 0) refs.current[i - 1]?.focus();
              }}
              inputMode="numeric"
              maxLength={1}
              className={`w-full min-w-0 h-[66px] rounded-[16px] text-center text-[24px] font-bold outline-none transition-colors font-body ${
                error
                  ? "bg-danger-50 border-2 border-danger-500 text-danger-700"
                  : "bg-background-100 border border-background-200 text-foreground-950 focus:border-foreground-950"
              }`}
            />
          ))}
        </div>

        {error && (
          <div className="flex items-center justify-center gap-1.5 mt-4 text-danger-600">
            <i className="ri-error-warning-line text-[16px] leading-none" />
            <span className="text-[13px] font-medium">{errorLabel}</span>
          </div>
        )}

        <div className="flex flex-col items-center gap-2 mt-8">
          {seconds > 0 ? (
            <span className="text-[13px] text-foreground-500">
              إعادة الإرسال خلال{" "}
              <span className="font-semibold text-foreground-900" dir="ltr">
                00:{String(seconds).padStart(2, "0")}
              </span>
            </span>
          ) : (
            <button
              type="button"
              onClick={() => {
                setSeconds(45);
                setError(false);
              }}
              className="text-[13.5px] font-semibold text-foreground-950 underline underline-offset-2 cursor-pointer"
            >
              إعادة إرسال الكود
            </button>
          )}
          <button
            type="button"
            onClick={() => setDigits(["1", "2", "3", "4"])}
            className="text-[11.5px] text-foreground-400 cursor-pointer"
          >
            تجربة حالة الخطأ (1 2 3 4)
          </button>
        </div>
      </div>

      <div className="px-5 py-5 pb-[calc(env(safe-area-inset-bottom)+1.25rem)]">
        <Btn full disabled={!filled || verifying} onClick={confirm}>
          {verifying ? "جاري التحقق..." : confirmLabel}
        </Btn>
      </div>
    </div>
  );
}