"use client";

import { useState, useEffect } from "react";
import Link from "next/link";

const WECHAT_STORAGE_KEY = "salon_join_wechat";

function clearPendingOrder(): void {
  try {
    localStorage.removeItem("join_pay_order");
  } catch {}
  document.cookie = "join_pay_order=; path=/; max-age=0";
}

export default function JoinPaidPage() {
  const [completeStatus, setCompleteStatus] = useState<"pending" | "success" | "error">("pending");
  const [errorDetail, setErrorDetail] = useState<string | null>(null);
  const [countdown, setCountdown] = useState<number | null>(null);
  const [wechatId, setWechatId] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    const tryComplete = async (orderId: string): Promise<{ ok: boolean; error?: string; record?: { wechatId?: string } }> => {
      const r = await fetch("/api/salon/complete-order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ order_id: orderId }),
        credentials: "include",
      });
      const d = await r.json();
      if (!d?.ok) return { ok: false, error: d?.error || d?.detail || `HTTP ${r.status}` };

      if (d?.token && d?.record) {
        await fetch("/api/auth/sync-session", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token: d.token, record: d.record }),
          credentials: "include",
        });
        const { pbSaveAuth } = await import("@/app/lib/pocketbase");
        pbSaveAuth(d.token, d.record);
      }
      window.dispatchEvent(new CustomEvent("auth:updated"));
      window.dispatchEvent(new CustomEvent("vip:updated"));
      return { ok: true, record: d?.record };
    };

    const run = async () => {
      const urlOrderId = typeof window !== "undefined"
        ? new URLSearchParams(window.location.search).get("order_id") || ""
        : "";
      const cookie = document.cookie.split(";").find((c) => c.trim().startsWith("join_pay_order="));
      const rawValue = cookie?.split("=")[1]?.trim();
      const storageValue = (() => {
        try {
          return localStorage.getItem("join_pay_order") || "";
        } catch {
          return "";
        }
      })();
      const decoded = rawValue ? decodeURIComponent(rawValue) : storageValue;
      const orderId = urlOrderId || decoded.split("|")[0]?.trim() || "";
      if (!orderId) {
        clearPendingOrder();
        window.location.replace("/join");
        return;
      }

      const maxClientRetries = 5;
      const retryDelays = [2000, 3000, 4000, 5000, 6000];
      let lastError = "";
      for (let i = 0; i <= maxClientRetries; i++) {
        if (cancelled) return;
        try {
          const result = await tryComplete(orderId);
          if (result.ok) {
            clearPendingOrder();
            if (!cancelled) {
              setCompleteStatus("success");
              if (result.record?.wechatId) setWechatId(result.record.wechatId);
            }
            return;
          }
          lastError = result.error || "unknown";
        } catch (e) {
          lastError = e instanceof Error ? e.message : "network error";
        }
        if (i < maxClientRetries) {
          await new Promise((r) => setTimeout(r, retryDelays[i]));
        }
      }
      if (!cancelled) {
        setCompleteStatus("error");
        setErrorDetail(lastError);
      }
    };
    run();

    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(WECHAT_STORAGE_KEY)?.trim();
      if (stored) setWechatId(stored);
    } catch {
      /* ignore */
    }
  }, []);

  const COUNTDOWN_SECONDS = 5;
  useEffect(() => {
    if (completeStatus !== "success") return;
    setCountdown(COUNTDOWN_SECONDS);
    const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev == null || prev <= 1) {
            clearInterval(timer);
            window.location.replace("/join?paid=1");
            return 0;
          }
          return prev - 1;
        });
    }, 1000);
    return () => clearInterval(timer);
  }, [completeStatus]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-[#f0f4f8] dark:bg-gray-950 px-4">
      <div className="w-full max-w-md animate-fade-in rounded-2xl bg-white dark:bg-gray-900 p-10 text-center shadow-lg border border-gray-100 dark:border-gray-800">
        <div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-emerald-50 dark:bg-emerald-900/30 text-5xl">
          ✅
        </div>
        <h2 className="text-2xl font-bold text-slate-800 dark:text-slate-100">
          {completeStatus === "pending" ? "处理中…" : completeStatus === "success" ? "支付成功" : "处理异常"}
        </h2>
        <p className="mt-3 text-slate-500 dark:text-slate-400">
          {completeStatus === "success"
            ? countdown != null
              ? `${countdown} 秒后跳转报名成功页`
              : "感谢您的支持"
            : completeStatus === "error"
              ? "请稍后刷新页面重试"
              : "正在确认支付状态…"}
        </p>
        {wechatId && (
          <p className="mt-2 text-xs text-slate-400 dark:text-slate-500 font-mono">微信号: {wechatId}</p>
        )}
        {completeStatus === "error" && errorDetail && (
          <p className="mt-1 text-xs text-slate-400 dark:text-slate-500">{errorDetail}</p>
        )}
        {completeStatus === "error" && (
          <button
            type="button"
            onClick={() => window.location.reload()}
            className="mt-4 rounded-full border border-[#ff4d4f] px-6 py-2.5 text-sm font-medium text-[#ff4d4f] hover:bg-[#ff4d4f]/10 transition-colors"
          >
            刷新重试
          </button>
        )}
        {completeStatus === "pending" ? (
          <span className="mt-8 inline-flex items-center gap-2 rounded-full bg-stone-200 dark:bg-stone-700 px-8 py-3 font-semibold text-stone-400 dark:text-stone-500 cursor-not-allowed">
            ← 查看报名状态
          </span>
        ) : (
          <Link
            href="/join?paid=1"
            className="mt-8 inline-flex items-center gap-2 rounded-full bg-[#ff4d4f] px-8 py-3 font-semibold text-white transition-colors hover:bg-[#ff7a45]"
          >
            ← 查看报名状态
          </Link>
        )}
      </div>
    </div>
  );
}
