"use client";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { updateUser } from "../../store/authSlice";
import { useAppDispatch } from "../../lib/hooks";
import { updateSession } from "../../lib/api/inventory";
import { setBalanceMode } from "@/app/lib/api/balanceMode";
import { User } from "@/constants/types";
import { useSelector } from "react-redux";

export function BalancePill({
  value,
  className = "",
  coins,
  gems,
  activeMode,
}: {
  value: number;
  className?: string;
  coins: number;
  gems: number;
  activeMode: string;
}) {
  const display = new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 1,
  }).format(value);

  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement | null>(null);
  const [selected, setSelected] = useState<"coins" | "gems">("coins");
  const [fakeModalOpen, setFakeModalOpen] = useState(false);
  const [switching, setSwitching] = useState(false);

  const user = useSelector((state: any) => state.auth.user) as User | null;
  const switchMode = async (mode: "coins" | "gems") => {
    if (switching) return;
    setSwitching(true);

    try {
      setSelected(mode);

      // ✅ wait BOTH calls (very important)
      await balanceModeHandler(mode);
      await updateMode(mode);

      setOpen(false);

      // ✅ full website reload after both are done
      window.location.reload();
    } catch (err) {
      console.error("Mode switch failed:", err);
      // optional: rollback UI
      // setSelected(prev => prev === "coins" ? "gems" : "coins");
    } finally {
      setSwitching(false);
    }
  };

  async function updateMode(mode: "coins" | "gems") {
    return await updateSession({ activeMode: mode });
  }

  const balanceModeHandler = async (mode: "coins" | "gems") => {
    try {
      return await setBalanceMode(user?.userId, user?.token, mode);
    } catch (e: any) {
      console.error("Error setting balance mode:", e.message);
      throw e; // important so click handler knows it failed
    }
  };

  // close on outside click
  useEffect(() => {
    // user?.activeMode === "gems" ? setSelected("gems") : setSelected("coins");
    const close = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    window.addEventListener("mousedown", close);
    return () => window.removeEventListener("mousedown", close);
  }, []);

  useEffect(() => {
    const mode = (user?.activeMode || activeMode) as
      | "coins"
      | "gems"
      | undefined;
    if (mode === "coins" || mode === "gems") setSelected(mode);
  }, [user?.activeMode, activeMode]);

  return (
    <div ref={ref} className={`relative ${className}`}>
      {/* MAIN PILL (WIN) */}
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center justify-center gap-2 h-13 px-5 light-black-bg w-full"
      >
        <img
          src={
            selected === "coins"
              ? "/images/header/win.svg"
              : "/images/header/star.svg"
          }
          className="h-6 w-6"
        />

        <p className="text-(--color-slate) font-extrabold text-xs md:text-base 2xl:text-xl">
          {selected === "coins" ? "WINCOINS" : "TCGGEMS"}
        </p>

        <span className="text-white font-bold text-xs md:text-base 2xl:text-xl">
          {selected === "coins" ? coins : gems}
        </span>

        <img src="/images/header/dropdown.svg" alt="" />
      </button>

      {/* DROPDOWN (dummy) */}
      {open && (
        <div className="absolute z-9999999 left-0 top-full mt-1 w-full light-black-bg shadow-xl">
          {/* TCG Wincoins */}
          <button
            onClick={() => switchMode("coins")}
            className="flex items-center justify-center md:justify-between cursor-pointer gap-2 py-4 border-b-2 border-(--color-gray) px-5 light-black-bg w-full"
          >
            <img src="/images/header/win.svg" alt="" className="h-6 w-6" />
            <p className="text-(--color-slate) font-extrabold text-xs md:text-base 2xl:text-xl ">
              WINCOINS
            </p>
            <span className="text-white font-bold text-xs md:text-base 2xl:text-xl ">
              {coins}
            </span>
          </button>

          {/* TCG Gems */}
          <button
            onClick={() => switchMode("gems")}
            className="flex items-center justify-center md:justify-between cursor-pointer border-b-2 border-(--color-gray) gap-2 py-4 px-5 light-black-bg w-full"
          >
            <img src="/images/header/star.svg" alt="" className="h-6 w-6" />
            <p className="text-(--color-slate) font-extrabold text-xs md:text-base 2xl:text-xl ">
              TCGGEMS
            </p>
            <span className="text-white font-bold text-xs md:text-base 2xl:text-xl ">
              {gems}
            </span>
            <span
              onClick={(e) => {
                e.stopPropagation();
                setFakeModalOpen(true);
              }}
              className="ml-1 w-4 h-4 shrink-0 cursor-pointer flex items-center justify-center"
              aria-label="Fake balance info"
            >
              <img
                src="/images/header/i.svg"
                alt="i"
                className="w-4 h-4 object-contain"
              />
            </span>
          </button>

          {/* Wallet link */}
          <Link
            href="/wallet"
            onClick={() => setOpen(false)}
            className="block text-center font-onest py-3 text-sm text-blue-400 hover:underline"
          >
            Go to Wallet
          </Link>
        </div>
      )}

      {fakeModalOpen && (
        <div className="fixed inset-0 z-999 flex items-center justify-center">
          {/* backdrop */}
          <button
            className="absolute inset-0 bg-black/60"
            onClick={() => setFakeModalOpen(false)}
            aria-label="Close"
          />

          {/* modal box */}
          <div className="relative w-[92%] max-w-md bg-(--color-darkBlue) p-6 shadow-2xl">
            <div className="flex items-start gap-3">
              <img src="/images/header/i.svg" className="h-7 w-7" alt="" />
              <div className="flex-1">
                <h3 className="text-white font-onest tracking-wide font-extrabold text-lg">
                  Fake Balance
                </h3>
                <p className="text-(--color-slate) font-onest text-sm mt-2 leading-relaxed">
                  This is your{" "}
                  <span className="text-white font-bold">fake balance</span>.
                  You can use it to explore the entire website, but you{" "}
                  <span className="text-white font-bold">cannot withdraw</span>,
                  cash out, or use it for any real-money transactions.
                </p>
              </div>

              <button
                onClick={() => setFakeModalOpen(false)}
                className="text-white/80 hover:text-white text-xl leading-none"
                aria-label="Close modal"
              >
                ✕
              </button>
            </div>

            <div className="mt-6 flex gap-3">
              <button
                onClick={() => setFakeModalOpen(false)}
                className="flex-1 py-3 bg-(--color-blue) text-white font-bold tracking-wide hover:opacity-90 transition"
              >
                Got it
              </button>
              <Link
                href="/wallet"
                onClick={() => setFakeModalOpen(false)}
                className="flex-1 text-center py-3 bg-(--color-slate) text-white font-bold tracking-wide hover:bg-white/15 transition"
              >
                Open Wallet
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
