import { useEffect, useRef, useState } from "react";
import { useApp } from "../AppContext";
import { BackHeader, Btn } from "../components/ui";

export default function Otp() {
  const { goBack, completeAuth, navigate, params } = 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;
      }
      if (params.flow === "bo") {
        navigate("boPending");
        return;
      }
      if (params.flow === "inv") {
        navigate("invPending");
        return;
      }
      completeAuth();
    }, 900);
  };

  return (
    <div className="min-h-full flex flex-col bg-background-50">
      <BackHeader title="أدخل كود التحقق" onBack={goBack} />

      <div className="flex-1 px-6 pt-8">
        <p className="text-[13.5px] text-foreground-600 leading-relaxed text-center">
          أرسلنا كود التحقق المكوّن من 4 أرقام إلى الرقم
        </p>
        <p className="text-[15px] font-semibold text-foreground-950 text-center mt-1" dir="ltr">
          +966 5X XXX XXXX
        </p>

        <div className="grid grid-cols-4 gap-3.5 w-full max-w-[288px] mx-auto mt-9" 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-[68px] 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">الكود غير صحيح</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="sticky bottom-0 z-30 px-5 py-5 bg-background-50 border-t border-background-200/70">
        <Btn full disabled={!filled || verifying} onClick={confirm}>
          {verifying ? "جاري التحقق..." : "تأكيد"}
        </Btn>
      </div>
    </div>
  );
}