"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";

import { safeNextUrl } from "@/lib/auth-navigation";
import {
  getAccessToken,
  getMe,
  sendPhoneOtp,
  verifyPhoneOtp,
  type MeUser,
  type WebAuthNormalizedError,
} from "@/lib/web-auth-client";

function viOtpError(err: WebAuthNormalizedError): string {
  const c = err.code;
  switch (c) {
    case "PHONE_INVALID":
      return "Số điện thoại chưa đúng định dạng Việt Nam.";
    case "OTP_COOLDOWN":
      return "Vui lòng chờ trước khi gửi lại mã.";
    case "PHONE_ALREADY_USED":
      return "Số điện thoại này đã được dùng cho tài khoản khác.";
    case "OTP_EXPIRED_OR_INVALID":
      return "Mã OTP không đúng hoặc đã hết hạn.";
    case "OTP_TOO_MANY_ATTEMPTS":
      return "Bạn đã nhập sai quá số lần cho phép. Hãy gửi mã mới.";
    case "PHONE_ALREADY_VERIFIED":
      return "Số điện thoại đã được xác minh.";
    default:
      return err.message || "Đã có lỗi xảy ra.";
  }
}

function VerifyPhoneFormInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextDest = safeNextUrl(searchParams.get("next"), "/");

  const [booting, setBooting] = useState(true);
  const [me, setMe] = useState<MeUser | null>(null);
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [sendLoading, setSendLoading] = useState(false);
  const [verifyLoading, setVerifyLoading] = useState(false);
  const [cooldown, setCooldown] = useState(0);

  useEffect(() => {
    if (cooldown <= 0) return;
    const id = window.setInterval(() => {
      setCooldown((s) => (s <= 1 ? 0 : s - 1));
    }, 1000);
    return () => window.clearInterval(id);
  }, [cooldown]);

  useEffect(() => {
    let alive = true;
    (async () => {
      const token = getAccessToken();
      if (!token) {
        router.replace(`/login?next=${encodeURIComponent("/verify-phone")}`);
        return;
      }
      try {
        const { user } = await getMe();
        if (!alive) return;
        if (!user.requiresPhoneVerification) {
          router.replace(nextDest);
          return;
        }
        setMe(user);
      } catch {
        if (!alive) return;
        router.replace(`/login?next=${encodeURIComponent("/verify-phone")}`);
      } finally {
        if (alive) setBooting(false);
      }
    })();
    return () => {
      alive = false;
    };
  }, [router, nextDest]);

  async function onSendOtp(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!phone.trim()) {
      setError("Vui lòng nhập số điện thoại.");
      return;
    }
    setSendLoading(true);
    try {
      const r = await sendPhoneOtp(phone.trim());
      setCooldown(r.cooldownSeconds ?? 60);
    } catch (caught: unknown) {
      setError(viOtpError(caught as WebAuthNormalizedError));
    } finally {
      setSendLoading(false);
    }
  }

  async function onVerify(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    const c = code.trim();
    if (c.length !== 6 || !/^\d{6}$/.test(c)) {
      setError("Mã OTP cần đúng 6 chữ số.");
      return;
    }
    setVerifyLoading(true);
    try {
      await verifyPhoneOtp(phone.trim(), c);
      router.replace(nextDest);
    } catch (caught: unknown) {
      setError(viOtpError(caught as WebAuthNormalizedError));
    } finally {
      setVerifyLoading(false);
    }
  }

  if (booting) {
    return (
      <p className="mt-10 text-center text-sm text-stone-500" role="status">
        Đang tải…
      </p>
    );
  }

  return (
    <div className="mt-10 space-y-10">
      {me?.phoneNumberMasked ? (
        <p className="rounded-lg border border-stone-800/60 bg-black/20 px-3 py-2 text-center text-sm text-stone-400">
          Số đang gắn tài khoản (đã ẩn): <span className="text-amber-200/85">{me.phoneNumberMasked}</span>
        </p>
      ) : null}

      {error ? (
        <p
          className="rounded-lg border border-red-900/40 bg-red-950/25 px-3 py-2 text-sm text-red-200/90"
          role="alert"
        >
          {error}
        </p>
      ) : null}

      <section className="rounded-2xl border border-amber-950/25 bg-stone-950/35 px-5 py-6 sm:px-6 sm:py-7">
        <h2 className="font-ctkp-display text-base font-semibold text-amber-100/90">Bước 1 — Gửi mã</h2>
        <form onSubmit={onSendOtp} className="mt-4 space-y-4">
          <div>
            <label htmlFor="vp-phone" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Số điện thoại
            </label>
            <input
              id="vp-phone"
              name="phone"
              type="tel"
              inputMode="tel"
              autoComplete="tel"
              placeholder="090… hoặc +84…"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-black/30 px-3 py-2.5 text-[15px] text-stone-100 outline-none ring-amber-900/25 focus:ring-2"
            />
          </div>
          <button
            type="submit"
            disabled={sendLoading || cooldown > 0}
            className="w-full rounded-xl border border-amber-700/45 bg-amber-950/45 py-2.5 text-sm font-medium text-amber-50/95 transition hover:bg-amber-950/65 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {cooldown > 0 ? `Gửi lại sau ${cooldown}s` : sendLoading ? "Đang gửi…" : "Gửi mã OTP"}
          </button>
        </form>
      </section>

      <section className="rounded-2xl border border-amber-950/25 bg-stone-950/35 px-5 py-6 sm:px-6 sm:py-7">
        <h2 className="font-ctkp-display text-base font-semibold text-amber-100/90">Bước 2 — Nhập mã</h2>
        <p className="mt-1 text-xs leading-relaxed text-stone-500">
          Trong môi trường dev, mã hiện trên console backend (không hiện ở đây).
        </p>
        <form onSubmit={onVerify} className="mt-4 space-y-4">
          <div>
            <label htmlFor="vp-code" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Mã 6 số
            </label>
            <input
              id="vp-code"
              name="code"
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={6}
              autoComplete="one-time-code"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-black/30 px-3 py-2.5 text-[15px] tracking-[0.35em] text-stone-100 outline-none ring-amber-900/25 focus:ring-2"
            />
          </div>
          <button
            type="submit"
            disabled={verifyLoading}
            className="w-full rounded-xl border border-amber-700/45 bg-amber-950/45 py-2.5 text-sm font-medium text-amber-50/95 transition hover:bg-amber-950/65 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {verifyLoading ? "Đang xác minh…" : "Xác minh"}
          </button>
        </form>
      </section>
    </div>
  );
}

export default function VerifyPhonePage() {
  return (
    <main className="mx-auto max-w-[1100px] flex-1 px-4 py-16 sm:px-8 sm:py-20">
      <article className="mx-auto max-w-md">
        <header className="text-center">
          <div className="ctkp-rule mx-auto mb-8 w-20 opacity-80" aria-hidden />
          <p className="ctkp-eyebrow tracking-[0.36em]">Cổ Thư Kỳ Tịch · xác minh</p>
          <h1 className="font-ctkp-display mt-5 text-[1.85rem] font-semibold leading-tight tracking-tight text-stone-100 sm:text-[2rem]">
            Xác minh số điện thoại
          </h1>
          <p className="mt-3 text-sm leading-relaxed text-stone-500">
            Beta yêu cầu số thật — một lần gửi mã, một lần ghi nhận.
          </p>
        </header>
        <Suspense
          fallback={
            <p className="mt-10 text-center text-sm text-stone-500" role="status">
              Đang tải…
            </p>
          }
        >
          <VerifyPhoneFormInner />
        </Suspense>
        <p className="mt-10 text-center">
          <Link href="/" className="ctkp-text-link text-sm">
            ← Về trang chủ
          </Link>
        </p>
      </article>
    </main>
  );
}
