"use client";
import AddedToInventory from "@/app/components/mystery-packs/AddedToInventory";
import MysteryHeader from "@/app/components/mystery-packs/MysteryHeader";
import OgBox from "@/app/components/mystery-packs/OgBox";
import PackDetailLayout from "@/app/components/mystery-packs/PackDetailLayout";
import PacksGrid from "@/app/components/mystery-packs/PacksGrid";
import { toPackUI } from "@/app/components/mystery-packs/PackUI";
import AlertModal from "@/app/components/ui/AlertModal";
import NotAvailable from "@/app/components/ui/NotAvailable";
import { updateSession } from "@/app/lib/api/inventory";
import { buySlab, fetchSlab, fetchSlabAnalytics } from "@/app/lib/api/slab";
import { useAppDispatch } from "@/app/lib/hooks";
import { updateUser } from "@/app/store/authSlice";
import { User } from "@/constants/types";
import { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";

export type MysteryPack = {
  id: number;
  title: string;
  tier: string;
  price: string;
  image: string;
  backImage: string;
};

type SlabCard = {
  card_title: string;
  price: string;
  cover_image: string;
};

export type SlabAnalytics = {
  cards: SlabCard[];
  "5_15"?: number;
  "15_30"?: number;
  "30_100"?: number;
  "100_250"?: number;
  "250_300"?: number;
  "300_450"?: number;
};

export const PACKS: MysteryPack[] = [
  {
    id: 1,
    title: "BASIC MYSTERY SLAB PACK",
    tier: "BASIC",
    price: "25",
    image: "/images/mystery-packs/4.svg",
    backImage: "/images/mystery-packs/whiteback.svg",
  },
  {
    id: 2,
    title: "PRO MYSTERY SLAB PACK",
    tier: "PRO BLUE",
    price: "50",
    image: "/images/mystery-packs/1.svg",
    backImage: "/images/mystery-packs/blueback.svg",
  },
  {
    id: 3,
    title: "GOLD MYSTERY SLAB PACK",
    tier: "GOLD",
    price: "100",
    image: "/images/mystery-packs/3.svg",
    backImage: "/images/mystery-packs/goldback.svg",
  },
  {
    id: 4,
    title: "ELITE MYSTERY SLAB PACK",
    tier: "ELITE",
    price: "200",
    image: "/images/mystery-packs/2.svg",
    backImage: "/images/mystery-packs/redback.svg",
  },
];

const Inner = () => {
  const [boltMode, setBoltMode] = useState(false);
  const [pack, setPack] = useState<MysteryPack | null>(null);
  const [isAnimating, setIsAnimating] = useState(false);
  const [showResult, setShowResult] = useState(false);
  const [showHighlight, setShowHighlight] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const [isBuying, setIsBuying] = useState(false);
  const [slabCard, setSlabCard] = useState<any>(null);
  const [balance, setBalance] = useState<number | null>(null);
  const [viewPacks, setViewPacks] = useState<boolean>(false);
  const [isCardBuying, setIsCardBuying] = useState(false);
  const [selectedId, setSelectedId] = useState<any>(PACKS[0]?.id ?? "");
  const [slabAnalytics, setSlabAnalytics] = useState<SlabAnalytics>({
    cards: [],
  });
  const [slabAnaylyticsLoading, setSlabAnalyticsLoading] =
    useState<boolean>(false);
  const dispatch = useAppDispatch();

  const user = useSelector((state: any) => state.auth.user) as User | null;
  const speedFactor = boltMode ? 0.4 : 1;

  const flipDurationMs = 3500 * speedFactor; // old: 3500
  const shineDurationSec = 2.1 * speedFactor; // CSS diag shine

  const parseAmount = (price: string) => {
    const n = Number(String(price).replace(/[^0-9.]/g, ""));
    return Number.isFinite(n) ? n : 0;
  };

  const highlightDurationMs = 1500;

  const handlerBuySlab = async (selectedPack: MysteryPack) => {
    if (!user) {
      setModalType("error");
      setModalMsg("Please log in to make a purchase.");
      setModalOpen(true);
      return;
    }

    const amount = parseAmount(selectedPack.price);
    if (!amount) {
      setModalType("error");
      setModalMsg("Invalid pack price.");
      setModalOpen(true);
      return;
    }
    setIsCardBuying(true);
    try {
      const apiRes = await buySlab({
        userId: (user as any)?.userId || (user as any)?.user_id,
        amount,
        token: user.token,
      });
      console.log("apiRes", apiRes);
      if (apiRes.resp === "error") {
        setModalType("error");
        setModalMsg(apiRes.msg || "Purchase failed.");
        setModalOpen(true);
        setIsCardBuying(false);
        return;
      }

      if (apiRes.resp === "success") {
        setSlabCard(apiRes.card ?? null);
        setBalance(apiRes.balance ?? null);
      }
      setIsBuying(true);
      setIsCardBuying(false);
      setPack(selectedPack);
      setIsAnimating(true);
      setShowHighlight(false);
      setShowResult(false);

      setTimeout(() => {
        setIsAnimating(false);

        if (apiRes.resp !== "success") {
          setModalType("error");
          setModalMsg(apiRes.msg || "Purchase failed.");
          setModalOpen(true);

          setShowHighlight(false);
          setShowResult(false);
          setPack(null);
          return;
        }

        setShowHighlight(true);

        setTimeout(async () => {
          // success side effects
          dispatch(updateUser({ coins: apiRes?.coins, gems: apiRes?.gems }));
          await updateSession({ coins: apiRes?.coins, gems: apiRes?.gems });

          setModalType("success");
          setModalMsg("Purchase successful! Added to inventory.");
          setModalOpen(true);

          // 3) Final result UI
          setShowResult(true);
        }, highlightDurationMs);
      }, flipDurationMs);
    } catch (e: any) {
      setModalType("error");
      setModalMsg(e?.message || "Something went wrong.");
      setModalOpen(true);

      setShowResult(false);
      setShowHighlight(false);
      setPack(null);
    } finally {
      setIsBuying(false);
    }
  };

  const getSlabAnalytics = async (amount: any) => {
    setSlabAnalyticsLoading(true);
    try {
      const res = await fetchSlabAnalytics(user?.token, amount);
      console.log("res", res);
      setSlabAnalytics(res);
      if (res.resp === "error") {
        setModalType("error");
        setModalMsg(res?.message);
        setModalOpen(true);
      }
      setSlabAnalyticsLoading(false);
    } catch (e: any) {
      setModalType("error");
      setModalMsg(e?.message || "Something went wrong.");
      setModalOpen(true);
    } finally {
      setSlabAnalyticsLoading(false);
    }
  };

  const packsUI = useMemo(() => toPackUI(PACKS), []);

  const selectedPack = useMemo(
    () => packsUI.find((p: any) => p.id === selectedId) ?? packsUI[0],
    [packsUI, selectedId],
  );

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          <div className="z-10">
            <div className="container mx-auto px-4 md:px-0 py-4">
              {pack ? (
                <>
                  {/* {showResult && ( */}
                  <OgBox
                    checked={boltMode}
                    setBoltMode={(next) => setBoltMode(next)}
                  />
                  {/* )} */}
                  <section
                    className={` ${
                      showResult && "bg-[#161E2A]"
                    } relative py-5 md:py-8 h-80 md:min-h-125  2xl:h-150 overflow-hidden`}
                  >
                    {!showResult && (
                      <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-162.5 md:w-255 h-37.5 md:h-72.5 bg-[#2B5AFF] opacity-20 transition-all duration-500 blur-3xl rounded-full"></div>
                    )}

                    {isAnimating && (
                      <div className="absolute inset-0 flex justify-center mt-5 md:mt-10 2xl:mt-16 z-50">
                        <div className="pack-glow ">
                          <div
                            className="pack-3d-wrap"
                            style={{
                              ["--dur" as any]: `${(flipDurationMs * 0.6) / 1000}s`,
                            }}
                          >
                            {/* front image */}
                            <div className="pack-3d-spin">
                              <div className="pack-face-wrap front">
                                <img
                                  src={pack?.image}
                                  className="pack-face-img "
                                />
                              </div>

                              {/* back images */}
                              <div className="pack-face-wrap back">
                                <div className="face-shine">
                                  <img
                                    src={pack?.backImage}
                                    className="pack-face-img"
                                  />
                                  {/* <span
                                className="shine-layer"
                                style={{
                                  animationDuration: `${shineDurationSec}s`,
                                }}
                              /> */}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}

                    {showHighlight && !showResult && slabCard?.cover_image && (
                      <div className="absolute inset-0 flex items-center justify-center z-50">
                        <div className="relative shine-wrapper">
                          <img
                            // src="/images/mystery-packs/5.svg"
                            src={slabCard?.cover_image}
                            alt=""
                            className="relative z-10 h-64 w-auto object-contain"
                          />
                          <span
                            className="shine-layer"
                            style={{
                              animationDuration: `${shineDurationSec}s`,
                            }}
                          />
                        </div>
                      </div>
                    )}

                    {/* 3) Final result UI */}
                    {/* showResult */}
                    {showResult && (
                      <AddedToInventory
                        image={slabCard.cover_image}
                        title="2025 rockets mewtwo ex"
                        subtitle="hyper rare"
                        onBuyAnother={() => handlerBuySlab(pack)}
                        onClose={() => setPack(null)}
                      />
                    )}
                  </section>
                </>
              ) : (
                <>
                  <MysteryHeader onBack={() => setViewPacks(false)} />

                  {viewPacks ? (
                    <>
                      <PackDetailLayout
                        packs={packsUI}
                        selectedPack={selectedPack}
                        isBuying={isBuying}
                        onSelect={(id) => setSelectedId(id)}
                        onBack={() => setViewPacks(false)}
                        onBuy={(pack) => handlerBuySlab(pack)}
                        getSlabAnalytics={getSlabAnalytics}
                        slabAnalytics={slabAnalytics}
                        slabLoading={slabAnaylyticsLoading}
                        isCardBuying={isCardBuying}
                      />
                    </>
                  ) : (
                    <PacksGrid
                      packs={PACKS}
                      isBuying={isBuying}
                      onView={(pack: any) => {
                        setViewPacks(true);
                        setSelectedId(pack.id);
                        getSlabAnalytics(pack.price);
                      }}
                    />
                  )}
                </>
              )}
            </div>
          </div>
          <AlertModal
            open={modalOpen}
            type={modalType}
            message={modalMsg}
            onClose={() => setModalOpen(false)}
          />
        </>
      )}
    </div>
  );
};

export default Inner;

// const getSlab = async () => {
//   try {
//     const res = await fetchSlab(user?.userId, user?.token, 5);
//     console.log("res", res);
//     if (res.resp === "error") {
//       setModalType("error");
//       setModalMsg(res?.message);
//       setModalOpen(true);
//     }
//   } catch (e: any) {
//     setModalType("error");
//     setModalMsg(e?.message || "Something went wrong.");
//     setModalOpen(true);
//   }
// };
