   "use client";
import React, { useEffect, useMemo, useState } from "react";
import { PackCard } from "../components/shop/PackCard";
import { Header } from "../components/shop/Header";
import { Cart } from "../components/shop/Cart";
import { QuantityControl } from "../components/shop/QuantityControl";
import { CardDisplay } from "../components/shop/CardDisplay";
import Image from "next/image";
import { ApiPack, PackData } from "../types/packs";
import { fetchCardsForPack, fetchPacks, getPackImageUrl } from "../lib/api";
import { saveOrder } from "../lib/api/shop";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import AlertModal from "../components/ui/AlertModal";

// Types
interface Card {
  id: number;
  name: string;
  image: string;
}
interface highValCard {
  price: any;
  id: number;
  name: string;
  image: string;
}

interface CartItem {
  packId: number;
  packName: string;
  quantity: number;
  price: number;
}

const ODDS_BY_BRAND: Record<string, { label: string; value: string }[]> = {
  pokemon: [
    { label: "Double Rare:", value: "1/5" },
    { label: "Ultra Rare:", value: "1/12" },
    { label: "Illustration Rare:", value: "1/9" },
    { label: "Special Illustration Rare:", value: "1/101" },
    { label: "Mega Hyper Rare:", value: "1/1260" },
  ],
  lorcana: [
    { label: "Cold Foil:", value: "1/12" },
    { label: "Enchanted:", value: "1/96" },
    { label: "Legendary:", value: "1/24" },
    { label: "Super Rare:", value: "1/8" },
    { label: "Rare:", value: "1/3" },
  ],
  magic: [
    { label: "Mythic Rare:", value: "1/8" },
    { label: "Rare:", value: "7/8" },
    { label: "Foil (any):", value: "1/3" },
    { label: "Special Treatment:", value: "1/45" },
    { label: "Serialized:", value: "1/2500" },
  ],
};

import { updateUser } from "../store/authSlice";
import { useAppDispatch } from "../lib/hooks";
import { updateSession } from "../lib/api/inventory";

// Main Component
const TradingCardShopInner: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>("pokemon");
  const [isLoadingPacks, setIsLoadingPacks] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [packs, setPacks] = useState<PackData[]>([]);
  const [selectedPackId, setSelectedPackId] = useState<number | null>(null);
  const [isLoadingCards, setIsLoadingCards] = useState<boolean>(false);
  const [cardsByPackId, setCardsByPackId] = useState<Record<number, Card[]>>(
    {},
  );
  const [quantities, setQuantities] = useState<Record<number, number>>({});
  const [cart, setCart] = useState<CartItem[]>([]);
  const [isSetModalOpen, setIsSetModalOpen] = useState(false);
  const [packById, setPackById] = useState<Record<number, PackData>>({});
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const [isOddsModalOpen, setIsOddsModalOpen] = useState(false);
  const [cardLimit, setCardLimit] = useState(6);
 const chatOpen = useSelector((state: any) => state.ui.chatOpen)
  const dispatch = useAppDispatch();

  const user = useSelector((state: any) => state.auth.user) as User | null;

  const selectedOdds = useMemo(() => {
    // activeTab values: "pokemon" | "lorcana" | "magic" etc
    return ODDS_BY_BRAND[activeTab] ?? ODDS_BY_BRAND.pokemon;
  }, [activeTab]);

  // 🔹 Packs + default selected pack load
  const loadPacks = async (brand: string) => {
    try {
      setIsLoadingPacks(true);
      setError(null);

      const apiPacks: ApiPack[] = await fetchPacks(brand);
      const mapped: PackData[] = apiPacks.map((pack) => ({
        id: pack.id,
        name: pack.name,
        price: pack.price,
        packImage: pack.image,
        image: pack.image,
        cards: [],
      }));

      setPacks(mapped);
      setPackById((prev) => {
        const next = { ...prev };
        mapped.forEach((p) => {
          next[p.id] = p;
        });
        return next;
      });
      if (mapped.length > 0) {
        const firstPack = mapped[0];
        setSelectedPackId(firstPack.id);
        fetchCardsForSelected(firstPack.id, true);
      }
    } catch (err: any) {
      console.error(err);
      setError(err.message ?? "Something went wrong while loading packs");
    } finally {
      setIsLoadingPacks(false);
    }
  };

  const fetchCardsForSelected = async (packId: number, initial = false) => {
    try {
      setIsLoadingCards(true);
      const cards = await fetchCardsForPack(packId);
      setCardsByPackId((prev) => ({
        ...prev,
        [packId]: cards,
      }));
    } catch (err: any) {
      console.error(err);
      setError(err.message ?? "Something went wrong while loading cards");
      if (initial) {
        setSelectedPackId(null);
      }
    } finally {
      setIsLoadingCards(false);
    }
  };

  const selectedPack = useMemo(() => {
    if (!selectedPackId) return null;
    const pack = packs.find((p) => p.id === selectedPackId);
    if (!pack) return null;

    const cards = cardsByPackId[selectedPackId] || [];
    return {
      ...pack,
      cards,
    };
  }, [packs, selectedPackId, cardsByPackId]);

  //  Pack click handler
  const handlePackClick = async (pack: PackData) => {
    setSelectedPackId(pack.id);

    if (cardsByPackId[pack.id]) return;

    try {
      setIsLoadingCards(true);
      const cards = await fetchCardsForPack(pack.id);

      setCardsByPackId((prev) => ({
        ...prev,
        [pack.id]: cards,
      }));
    } catch (err: any) {
      console.error(err);
      setError(err.message ?? "Something went wrong while loading cards");
    } finally {
      setIsLoadingCards(false);
    }
  };

  // ---------- sync cart from quantities ----------
  const syncCartFromQuantities = (nextQuantities: Record<number, number>) => {
    const items: CartItem[] = [];

    Object.entries(nextQuantities).forEach(([idStr, qty]) => {
      const id = Number(idStr);
      if (qty <= 0) return;

      const pack = packById[id];
      if (!pack) return;

      items.push({
        packId: pack.id,
        packName: pack.name,
        quantity: qty,
        price: pack.price,
      });
    });

    setCart(items);
  };

  const handleIncrease = (packId: number) => {
    setQuantities((prev) => {
      const qty = (prev[packId] ?? 0) + 1;
      const next = { ...prev, [packId]: qty };
      syncCartFromQuantities(next);
      return next;
    });
  };

  const handleDecrease = (packId: number) => {
    setQuantities((prev) => {
      const current = prev[packId] ?? 0;
      const qty = Math.max(0, current - 1);
      const next = { ...prev };
      if (qty === 0) {
        delete next[packId];
      } else {
        next[packId] = qty;
      }
      syncCartFromQuantities(next);
      return next;
    });
  };

  const handlePurchase = async () => {
    if (!user) {
      setModalType("error"); // or "login" if you have a custom type
      setModalMsg("Please log in to complete your purchase.");
      setModalOpen(true);
      return;
    }
    try {
      if (!cart.length) {
        setModalType("error");
        setModalMsg("Cart is empty");
        setModalOpen(true);
        return;
      }

      const packsPayload = cart.map((item) => {
        const p = packById[item.packId];
        return {
          id: item.packId,
          name: item.packName,
          price: item.price,
          image: p?.image ?? p?.packImage ?? "",
          qty: item.quantity,
        };
      });

      const total = packsPayload.reduce((sum, p) => sum + p.price * p.qty, 0);

      const payload = {
        user_id: user.userId,
        brand: activeTab, // "pokemon"
        packs: packsPayload,
        total,
        discount: 0,
        token: user.token,
      };

      const result = await saveOrder(payload);

      if (result.resp === "success") {
        dispatch(updateUser({ coins: result?.coins, gems: result?.gems }));
        await updateSession({ coins: result?.coins, gems: result?.gems });
        setModalType("success");
        setModalMsg(
          `${result.msg || "Order placed successfully!"}${
            result.balance !== undefined
              ? ` New balance: ${result.balance}`
              : ""
          }`,
        );

        setModalOpen(true);

        // clear cart
        setQuantities({});
        setCart([]);
      } else {
        setModalType("error");
        setModalMsg(result.msg || "Order failed");
        setModalOpen(true);
      }
    } catch (e: any) {
      console.error(e);
      setModalType("error");
      setModalMsg(e?.message || "Something went wrong");
      setModalOpen(true);
    }
  };

  const showMaxLimitModal = () => {
    setModalType("error");
    setModalMsg("Maximum quantity of 10,000 is allowed.");

    setModalOpen(true);
  };

  const handleTabChange = (tabId: string) => {
    setActiveTab(tabId);
    loadPacks(tabId);
  };

  const handleRemoveFromCart = (packId: number) => {
    setQuantities((prev) => {
      const next = { ...prev };
      delete next[packId];
      syncCartFromQuantities(next);
      return next;
    });
  };

  const getPlaceholderByTab = (activeTab: any) => {
    if (activeTab === "pokemon") return "/cards/images/packs/battle-styles.png";
    if (activeTab === "lorcana")
      return "/cards/images/packs/archazia Island.png.png";
    return "/cards/images/packs/aetherdrift.png";
  };

  const handleChangeQuantity = (packId: number, qty: number) => {
    setQuantities((prev) => {
      const next = { ...prev };

      const safeQty = Math.max(0, qty);

      if (safeQty === 0) {
        delete next[packId];
      } else {
        next[packId] = safeQty;
      }

      syncCartFromQuantities(next);
      return next;
    });
  };

  useEffect(() => {
    loadPacks(activeTab);
  }, []);

  useEffect(() => {
    const updateLimit = () => {
      // Mobile: < 640px (Tailwind sm)
      if (window.innerWidth < 640) {
        setCardLimit(8);
      } else {
        setCardLimit(6);
      }
    };

    updateLimit(); // initial
    window.addEventListener("resize", updateLimit);

    return () => window.removeEventListener("resize", updateLimit);
  }, []);

  return (
    <div className={`min-h-screen px-5 overflow-x-hidden bg-[#0B0F1A]`}>
      <Header activeTab={activeTab} onTabChange={handleTabChange} />

      <div className="container mx-auto py-8">
        {/* <div className="grid lg:grid-cols-3 gap-8"> */}
        <div className="grid gap-4 [grid-template-columns:repeat(auto-fit,minmax(300px,1fr))]">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-8">
            {selectedPack ? (
              <div className="flex flex-col md:flex-row md:items-start items-center gap-6 mb-8">
                <div className="w-full flex justify-center md:w-43.25 shrink-0">
                  {isLoadingPacks ? (
                    <div className=" flex w-full h-67.5 items-center justify-center">
                      <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                    </div>
                  ) : (
                    <Image
                      width={173}
                      height={317}
                      src={
                        selectedPack?.packImage?.trim()
                          ? selectedPack.packImage.replace(
                              "cardsimages",
                              "cards/images",
                            )
                          : getPlaceholderByTab(activeTab)
                      }
                      alt={selectedPack.name}
                      className="w-40 md:w-full h-full object-contain "
                    />
                  )}
                </div>
                <div className="md:w-2/3">
                  <h1 className="text-white text-sm md:text-2xl 2xl:text-[30px] uppercase font-sofia font-extrabold mb-1">
                    {selectedPack.name}
                  </h1>
                  <p className="text-(--color-slate) text-xs md:text-lg font-sofia text-[22px] mb-4">
                    Cards
                  </p>
                  {isLoadingCards || isLoadingPacks ? (
                    <div className=" flex w-full  h-34 items-center justify-center">
                      <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                    </div>
                  ) : (
                    <CardDisplay
                      cards={[...selectedPack.cards]
                        .sort(
                          (a: any, b: any) =>
                            Number(b?.price) - Number(a?.price),
                        )
                        .slice(0, cardLimit)}
                      limit={cardLimit}
                      chatOpen={chatOpen}
                    />
                  )}
                  <div className="flex gap-3 2xl:gap-5 mt-8 2xl:my-10 items-center flex-wrap flex-col md:flex-row justify-between">
                    <div className="flex flex-col  sm:flex-row items-center gap-4">
                      <button
                        className={`bg-(--color-blue) min-w-22.5 duration-300 border border-transparent hover:bg-(--color-hoverBlue) text-white font-onest text-xs md:text-sm 2xl:text-base font-medium py-2 2xl:py-3 px-4 2xl:px-8 transition-colors ${
                          isLoadingCards || isLoadingPacks
                            ? "cursor-not-allowed pointer-events-none"
                            : "cursor-pointer"
                        }`}
                        onClick={() => {
                          console.log("click");
                          setIsSetModalOpen(true);
                        }}
                      >
                        VIEW SET
                      </button>
                      <button
                        onClick={() => setIsOddsModalOpen(true)}
                        className="border min-w-22 border-white duration-300 hover:bg-(--color-gray) text-white font-onest text-xs md:text-sm 2xl:text-base font-medium py-2 2xl:py-3 px-4 2xl:px-8 transition-colors"
                      >
                        ODDS
                      </button>
                    </div>
                    <QuantityControl
                      quantity={quantities[selectedPack.id] || 0}
                      onIncrease={() => handleIncrease(selectedPack.id)}
                      onDecrease={() => handleDecrease(selectedPack.id)}
                      price={selectedPack.price}
                      loading={isLoadingCards || isLoadingPacks}
                      onChangeQuantity={(qty) =>
                        handleChangeQuantity(selectedPack.id, qty)
                      } // ✅ FIX
                      max={10000}
                      onMaxLimitReached={showMaxLimitModal}
                    />
                  </div>
                </div>
              </div>
            ) : (
              <h1 className="text-white uppercase text-center">
                no data found
              </h1>
            )}
          </div>

          {/* Cart Sidebar */}
          <div className="lg:col-span-1">
            <div className="">
              <Cart
                cart={cart}
                onPurchase={handlePurchase}
                onRemove={handleRemoveFromCart}
              />
            </div>
          </div>
        </div>
        {isLoadingPacks ? (
          <div className=" flex w-full h-65 items-center justify-center">
            <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
          </div>
        ) : (
          <div className="w-full mt-10 nice-scrollbar pb-6 overflow-x-auto">
            <div className="flex gap-4 min-w-full">
              {packs.length < 1 ? (
                <p className="text-white">No data found</p>
              ) : (
                <>
                  {packs.map((pack) => (
                    <div
                      key={pack.id}
                      className="basis-[10%] max-w-[10%] min-w-30"
                    >
                      <PackCard
                        pack={pack}
                        isSelected={selectedPackId === pack.id}
                        onClick={() => {
                          handlePackClick(pack);
                        }}
                        getPlaceholderByTab={getPlaceholderByTab}
                        activeTab={activeTab}
                      />
                    </div>
                  ))}
                </>
              )}
            </div>
          </div>
        )}
      </div>
      {isSetModalOpen && selectedPack && (
        <div
          onClick={() => setIsSetModalOpen(false)}
          className="fixed inset-0 cursor-pointer flex z-9999 items-center justify-center bg-black/10 bg-opacity-75 backdrop-blur-xs select-card-bg-shadow"
        >
          <div
            onClick={(e) => e.stopPropagation()}
            className="max-w-2xl z-50 relative bg-(--color-naviBlue) w-full 2xl:max-w-3xl p-4 px-6  pt-0 rounded-xl"
          >
            {/* Sticky Close Button */}
            <div className="sticky top-0 z-20 py-5 pr-1 flex justify-end">
              <button
                className="text-white text-lg bg-(--color-naviBlue) cursor-pointer transition-all duration-300 hover:scale-115"
                onClick={() => setIsSetModalOpen(false)}
              >
                ✕
              </button>
            </div>

            {/* Cards */}
            <div className="nice-scrollbar overflow-y-auto overflow-x-hidden max-h-75 md:max-h-100 2xl:max-h-150">
              <CardDisplay
                cards={selectedPack.cards}
                limit={selectedPack.cards.length}
              />
            </div>
          </div>
        </div>
      )}
      {isOddsModalOpen && (
        <div
          onClick={() => setIsOddsModalOpen(false)}
          className="fixed inset-0 cursor-pointer flex z-9999 items-center justify-center bg-black/10 bg-opacity-75 backdrop-blur-xs select-card-bg-shadow"
        >
          <div
            onClick={(e) => e.stopPropagation()}
            className="max-w-2xl z-50 relative bg-(--color-naviBlue) w-full 2xl:max-w-3xl p-4 2xl:p-6 pr-0 pt-0 rounded-xl"
          >
            {/* Sticky Close Button */}
            <div className="sticky top-0 z-20 py-5 pr-1 flex justify-end">
              <button
                className="text-white text-lg bg-(--color-naviBlue) px-4 cursor-pointer transition-all duration-300 hover:scale-115"
                onClick={() => setIsOddsModalOpen(false)}
              >
                ✕
              </button>
            </div>

            {/* Odds Content */}
            <div className="no-scrollbar overflow-y-auto mr-6 max-h-75 md:max-h-100 2xl:max-h-150 pb-4">
              <div className="px-2">
                <h2 className="text-white font-sofia font-extrabold text-xl 2xl:text-3xl italic mb-4">
                  ODDS
                </h2>

                <div className="space-y-0">
                  {selectedOdds.map((row, i) => (
                    <div key={i} className="py-3 border-b border-white/15">
                      <div className="flex items-center justify-between gap-6">
                        <div className="text-white/90 font-sofia italic text-lg 2xl:text-2xl">
                          {row.label}
                        </div>
                        <div className="text-white font-sofia italic text-lg 2xl:text-2xl">
                          {row.value}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      <AlertModal
        open={modalOpen}
        type={modalType}
        message={modalMsg}
        onClose={() => setModalOpen(false)}
      />
    </div>
  );
};

export default TradingCardShopInner;
