"use client";

/**
 * ورود / ثبت‌نام با کد پیامکی (Server Actions).
 * در حالت توسعه با SMS_PROVIDER=console، کد در ترمینال سرور چاپ و در همین فرم هم نمایش داده می‌شود.
 */
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { requestOtpAction, verifyOtpAction } from "@/server/actions/auth";
import { reloadUserState } from "@/lib/client/store";
import { faDigits, faNumber } from "@/lib/format";
import { mobileSchema, otpSchema } from "@/validation/common";

export function OtpForm({ next }: { next: string }) {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [step, setStep] = useState<"phone" | "code">("phone");
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [devCode, setDevCode] = useState<string>();
  const [error, setError] = useState("");
  const [seconds, setSeconds] = useState(0);

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

  function sendCode(e?: React.FormEvent) {
    e?.preventDefault();
    const parsed = mobileSchema.safeParse(phone);
    if (!parsed.success) return setError(parsed.error.issues[0].message);
    start(async () => {
      const res = await requestOtpAction(parsed.data);
      if (!res.ok) {
        setError(res.error);
        if (res.retryAfter) {
          setStep("code");
          setPhone(parsed.data);
          setSeconds(res.retryAfter);
        }
        return;
      }
      setPhone(res.phone!);
      setDevCode(res.devCode);
      setError("");
      setCode("");
      setStep("code");
      setSeconds(60);
    });
  }

  function verify(e: React.FormEvent) {
    e.preventDefault();
    const parsed = otpSchema.safeParse(code);
    if (!parsed.success) return setError(parsed.error.issues[0].message);
    start(async () => {
      const res = await verifyOtpAction(phone, parsed.data);
      if (!res.ok) return setError(res.error);
      await reloadUserState(); // سبد مهمان در سبد حساب ادغام شده است
      router.replace(next);
      router.refresh();
    });
  }

  return (
    <div className="mx-auto w-full max-w-sm">
      {step === "phone" ? (
        <form onSubmit={sendCode} noValidate className="space-y-5">
          <div>
            <h1 className="text-2xl font-extrabold">ورود یا ثبت‌نام</h1>
            <p className="mt-2 text-sm text-muted">شماره موبایل خود را وارد کنید تا کد تأیید برایتان پیامک شود.</p>
          </div>
          <label className="block">
            <span className="label">شماره موبایل</span>
            <input className="field text-base tracking-wider" type="tel" inputMode="numeric" autoComplete="tel" autoFocus value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="09xxxxxxxxx" maxLength={14} />
          </label>
          {error && <p className="text-xs font-medium" role="alert">⚠ {error}</p>}
          <button className="btn-primary w-full" disabled={pending}>{pending ? "در حال ارسال…" : "دریافت کد تأیید"}</button>
          <p className="text-[11px] leading-5 text-muted">ورود شما به معنای پذیرش قوانین و حریم خصوصی زهوراست.</p>
        </form>
      ) : (
        <form onSubmit={verify} noValidate className="space-y-5">
          <div>
            <h1 className="text-2xl font-extrabold">کد تأیید</h1>
            <p className="mt-2 text-sm text-muted">
              کد ۵ رقمی ارسال‌شده به <bdi className="font-bold text-ink">{faDigits(phone)}</bdi> را وارد کنید.{" "}
              <button type="button" className="underline" onClick={() => { setStep("phone"); setCode(""); setError(""); setDevCode(undefined); }}>
                ویرایش شماره
              </button>
            </p>
          </div>
          <input className="field h-14 text-center text-2xl tracking-[0.6em]" inputMode="numeric" autoComplete="one-time-code" autoFocus value={code} onChange={(e) => setCode(e.target.value)} maxLength={5} aria-label="کد تأیید" />
          {error && <p className="text-xs font-medium" role="alert">⚠ {error}</p>}
          {devCode && <p className="rounded-xl bg-mist p-3 text-xs">حالت توسعه (پیامک واقعی ارسال نمی‌شود): کد <b>{faDigits(devCode)}</b></p>}
          <button className="btn-primary w-full" disabled={pending}>{pending ? "در حال بررسی…" : "تأیید و ورود"}</button>
          <p className="text-center text-xs text-muted">
            {seconds > 0 ? (
              <>ارسال مجدد کد تا {faNumber(Math.floor(seconds / 60))}:{faDigits(String(seconds % 60).padStart(2, "0"))}</>
            ) : (
              <button type="button" className="underline" disabled={pending} onClick={() => sendCode()}>ارسال مجدد کد</button>
            )}
          </p>
        </form>
      )}
    </div>
  );
}
