"use client";
import Script from "next/script";
import { ethers } from "ethers";
import axios from "axios";
import Link from "next/link";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import ProgressGlowBar from "./ProgressGlowBar";
import AuthModal from "../auth/AuthModal";
import { API_BASE_URL, API_URL, BASE_URL } from "@/constants";
import { useSearchParams, useRouter } from "next/navigation";
import { User } from "@/constants/types";
import AlertModal from "../ui/AlertModal";
import { formatNumber } from "@/app/profile/page";

type XPBadgeProps = {
  status: string;
  user: User | null;
  xp: number; // current XP (e.g., 1000)
  level: number; // level number (e.g., 7)
  maxXp?: number; // XP to next level (default 1000)
  avatarSrc: string; // /public/...
  username?: string;
  compact?: boolean;
};

export function XPBadge({
  status,
  user,
  xp,
  level,
  maxXp = 1000,
  avatarSrc,
}: XPBadgeProps) {
  const [authOpen, setAuthOpen] = useState(false);
  const [image, setImage] = useState<string | undefined | null>(avatarSrc);
  const [prog, setProg] = useState(0);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const [appleReady, setAppleReady] = useState(false);
  const [loader, set_loader] = useState(false);

  const appleInitRef = useRef(false);

  const appleInitPromiseRef = useRef<Promise<void> | null>(null);

  const ensureAppleInit = () => {
    if (typeof window === "undefined") return Promise.reject(new Error("SSR"));

    // If already initialized (Apple SDK sets this)
    if ((window as any).__APPLEID_INIT_DONE__) {
      appleInitRef.current = true;
      setAppleReady(true);
      return Promise.resolve();
    }

    if (appleInitPromiseRef.current) return appleInitPromiseRef.current;

    appleInitPromiseRef.current = new Promise<void>((resolve, reject) => {
      const start = Date.now();

      const tick = () => {
        const AppleID = (window as any).AppleID as any;

        if (AppleID?.auth?.init) {
          try {
            AppleID.auth.init({
              clientId: "com.openthatpack.login",
              redirectURI: "https://openthatpack.com/login",
              scope: "email name",
              usePopup: true,
            });

            (window as any).__APPLEID_INIT_DONE__ = true; // ✅ persist across renders/HMR
            appleInitRef.current = true;
            setAppleReady(true);
            resolve();
            return;
          } catch (e) {
            reject(e);
            return;
          }
        }

        if (Date.now() - start > 8000) {
          reject(new Error("AppleID SDK not available (timeout)"));
          return;
        }

        setTimeout(tick, 50);
      };

      tick();
    });

    return appleInitPromiseRef.current;
  };

  type AppleIDAuth = {
    init(options: {
      clientId: string;
      redirectURI: string;
      scope?: string;
      usePopup?: boolean;
    }): void;
    signIn(): Promise<any>;
    signOut?(): Promise<any>;
  };

  type AppleIDGlobal = {
    auth?: AppleIDAuth;
  };

  const AppleSignIn = async () => {
    try {
      set_loader(true);

      // always init first (fresh window.AppleID)
      await ensureAppleInit();

      const AppleID = (window as any).AppleID as any;
      if (!AppleID?.auth?.signIn) {
        console.warn("Apple auth not available yet ⏳");
        set_loader(false);
        return;
      }

      const response = await AppleID.auth.signIn();
      console.log("Apple", response);

      // ---- keep your existing backend fetch from here ----
      fetch(API_URL + "login-apple", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ response }),
      })
        .then((res) => res.json())
        .then(async (data) => {
          if (data.resp === "success") {
            let u = data.user;
            await fetch("/api/auth/login", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ user: u }),
            }).then((resp) => {
              window.location.href = "/profile";
            });
          }
        })
        .catch((err) => console.error("Error sending data to backend:", err))
        .finally(() => set_loader(false));
    } catch (error) {
      console.log("Apple Login Error", error);
      set_loader(false);
    }
  };

  const showError = (msg: string) => {
    setModalType("error");
    setModalMsg(msg);
    setModalOpen(true);
  };

  async function loginWithMetaMask() {
    // if (!(window as any)?.ethereum) return alert("MetaMask not detected!");
    if (!(window as any)?.ethereum) {
      showError("MetaMask not detected!");
      return;
    }

    try {
      const provider = new ethers.BrowserProvider((window as any).ethereum);
      const signer = await provider.getSigner();
      const wallet = await signer.getAddress();

      // Step 1: Get nonce from Laravel
      const { data } = await axios.post(BASE_URL + "/api/meta-nonce", {
        wallet,
      });

      const nonce = data.nonce;
      const signature = await signer.signMessage(nonce);
      const res = await axios.post(BASE_URL + "/api/meta-verify", {
        wallet,
        signature,
        message: nonce,
        ref: localStorage.getItem("tcg_ref"),
      });

      const resp = res.data.resp;
      if (resp == "success") {
        localStorage.removeItem("tcg_ref");
        const u = res.data.user;
        await fetch("/api/auth/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ user: u }),
        }).then((resp) => {
          // localStorage.setItem("is_login", "1");
          window.location.href = "/profile";
        });
      } else if (resp == "error" && res.data.msg == "2fa") {
        setModalType("success");
        setModalMsg("2FA required");
        setModalOpen(true);
      } else {
        showError(res.data.message || res.data.msg || "Login failed");
      }
    } catch (error: any) {
      // ✅ ethers v6 + MetaMask reject
      if (
        error?.code === "ACTION_REJECTED" ||
        error?.info?.error?.code === 4001
      ) {
        showError("User rejected the request.");
        return;
      }

      // fallback clean message
      const msg =
        error?.reason ||
        error?.info?.error?.message ||
        error?.message ||
        "Something went wrong";

      // extra safety: trim junk after first line
      const cleanMsg =
        typeof msg === "string" ? msg.split("\n")[0] : "Something went wrong";

      showError(cleanMsg);
    }
  }

  useEffect(() => {
    let intervalId: string | number | NodeJS.Timeout | null | undefined = null;

    const isDismissed = () => localStorage.getItem("tcg_ref_dismissed") === "1";

    const checkRef = () => {
      if (isDismissed()) {
        if (intervalId) clearInterval(intervalId);
        return;
      }

      const ref = localStorage.getItem("tcg_ref");
      if (ref) {
        setAuthOpen(true);
        if (intervalId) clearInterval(intervalId);
      }
    };

    // page load pe
    checkRef();

    intervalId = setInterval(checkRef, 2000);

    const onStorage = (e: any) => {
      if (
        (e.key === "tcg_ref" && e.newValue) ||
        e.key === "tcg_ref_dismissed"
      ) {
        checkRef();
      }
    };

    window.addEventListener("storage", onStorage);

    return () => {
      if (intervalId) clearInterval(intervalId);
      window.removeEventListener("storage", onStorage);
    };
  }, []);

  useEffect(() => {
    if (status === "unauthenticated") {
      const ref = localStorage.getItem("tcg_ref");
      if (ref) setAuthOpen(true);
    }
  }, [status]);

  useEffect(() => {
    if (status == "authenticated") {
      const img = user?.image;
      if (img != "") {
        setImage(img);
      }
      let next = user?.level?.next ?? 0;
      let xp = user?.level?.xp ?? 0;
      // next = parseInt(next);
      // xp = parseInt(xp);
      if (typeof next === "string") {
        next = parseInt(next);
      }
      if (typeof xp === "string") {
        xp = parseInt(xp);
      }
      let p = 0;
      if (xp > 0) {
        p = (xp / next) * 100;
      }
      setProg(p);
    }
  }, [user]);

  return (
    <>
      <Script
        id="appleid-auth"
        src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"
        strategy="afterInteractive"
        onLoad={() => {
          console.log("Apple script loaded ✅");
          ensureAppleInit().catch((e) => console.error("Apple init error:", e));
        }}
      />

      <div className={`flex items-center gap-2 light-black-bg `}>
        {status == "unauthenticated" ? (
          <a
            href="#"
            onClick={() => setAuthOpen(true)}
            className="bg-(--color-blue) uppercase hover:bg-(--color-hoverBlue) duration-300 px-4 md:px-10 py-1 2xl:py-1.5 login-btn  w-full text-center cursor-pointer text-sm md:text-lg font-bold text-white tracking-wide"
          >
            Login
          </a>
        ) : (
          <>
            <Link href="/profile">
              <button
                type="button"
                className="relative w-8 ml-2 h-8 cursor-pointer rounded-full overflow-hidden ring-2 ring-white/10 shrink-0"
                aria-label="Open sign in"
              >
                <img
                  src={(image as string) || "/images/profile/img.svg"}
                  alt="avatar"
                  loading="lazy"
                  style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  className="object-contain "
                />
              </button>
            </Link>
            <div className="flex-1 p-1.5 min-w-36 2xl:min-w-44">
              <div className="flex pb-1 items-center justify-between">
                <span className="font-sofia font-extrabold text-white text-xs md:text-sm 2xl:text-base leading-none tracking-tight">
                  {formatNumber(user?.level?.xp)} <span className="opacity-90">XP</span>
                </span>

                {/* Right: diamond level */}
                <div className="hidden sm:flex items-center">
                  <div
                    className="relative mt-1.5 mr-2 rotate-45 w-5 h-5 rounded-md border border-[#2B5AFF]
                        shadow-[0_0_24px_6px_rgba(43,90,255,0.35)] bg-black/30"
                  >
                    <div className="absolute inset-0 rounded-md pointer-events-none" />
                    <div className="absolute inset-0 -rotate-45 flex items-center justify-center">
                      <span className="font-sofia font-extrabold text-white text-xs leading-none">
                        {formatNumber(user?.level?.lavel)}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <ProgressGlowBar
                value={Number(user?.level?.xp ?? 0)}
                max={user?.level?.next}
                height={11}
                // showLabel
                // label={`${user?.level.xp} XP`}
                // user={user}
              />
            </div>
          </>
        )}
        <AuthModal
          open={authOpen}
          onClose={() => setAuthOpen(false)}
          onGoogle={() => (window.location.href = API_BASE_URL + "auth/google")}
          onMetamask={() => loginWithMetaMask()}
          onAppleLogin={() => AppleSignIn()}
        />
        <AlertModal
          open={modalOpen}
          type={modalType}
          message={modalMsg}
          onClose={() => setModalOpen(false)}
        />
      </div>
    </>
  );
}
