import { InventoryCard } from "@/app/lib/api/inventory";
import { User } from "@/constants/types";
import React, { useEffect, useRef, useState } from "react";
import { getSocket } from "../utils/socket";

interface Item extends InventoryCard {
  selected?: boolean;
}

type SelectedInvCard = {
  inv_id: number;
  image: string;
  price: number;
  name: string;
  rarity?: string;
};

type SelectedCard = {
  cardId: string;
  qty: number;
};

export const JoinGameModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  user: User | null;
  cardLoading: boolean;
  cardsError: string | null;
  cards: InventoryCard[];
  playGame?: () => void;
  joinLocked?: boolean;
  onPlay?: (selectedCards: SelectedCard[]) => void;
  onTotalValueChange: (value: number) => void;
  gameState: string;
  onLoadMore: () => void;
  hasMore: boolean;
  isLoadingMore: boolean;
  onSelectedCardsChange?: (cards: SelectedInvCard[]) => void;
}> = ({
  isOpen,
  onClose,
  user,
  cards,
  cardLoading,
  cardsError,
  playGame,
  joinLocked,
  onPlay,
  onTotalValueChange,
  gameState,
  onLoadMore,
  hasMore,
  isLoadingMore,
  onSelectedCardsChange,
}) => {
  const [itemList, setItemList] = useState<Item[]>([]);

  // lazy loading States
  const STEP = 10; // load
  const [visibleCount, setVisibleCount] = useState(STEP);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const scrollRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    setTimeout(() => {
      if (gameState === "crashed") {
        setItemList([]);
        // playGame();
      }
    }, 4000);
  }, [gameState]);

useEffect(() => {
  if (!isOpen) return;

  setVisibleCount(STEP);
  setIsFetchingMore(false);

  // Reset selection only when modal opens
  setItemList((cards || []).map((c) => ({ ...c, selected: false })));

  requestAnimationFrame(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  });
}, [isOpen]); // ✅ cards removed


useEffect(() => {
  if (!isOpen) return;

  setItemList((prev) => {
    const prevSelected = new Map<number, boolean>();
    for (const p of prev) prevSelected.set(p.inv_id, !!p.selected);

    return (cards || []).map((c) => ({
      ...c,
      selected: prevSelected.get(c.inv_id) ?? false, // ✅ preserve selection
    }));
  });
}, [cards, isOpen]);


  const toggleItemSelection = (id: number) => {
    setItemList((prevItems) =>
      prevItems.map((item) =>
        item.inv_id === id ? { ...item, selected: !item.selected } : item,
      ),
    );
  };

  const selectedCount = itemList.filter((item) => item.selected).length;
  const totalValue = itemList
    .filter((item) => item.selected)
    .reduce((sum, item) => sum + item.price, 0);

  useEffect(() => {
    onTotalValueChange(totalValue);
  }, [totalValue, onTotalValueChange]);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const el = e.currentTarget;
    const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 120;
    if (!nearBottom) return;

    // ✅ 1) First: show more from already-loaded list
    if (!isFetchingMore && visibleCount < itemList.length) {
      setIsFetchingMore(true);
      setTimeout(() => {
        setVisibleCount((c) => Math.min(c + STEP, itemList.length));
        setIsFetchingMore(false);
      }, 150);
      return;
    }

    // ✅ 2) Second: if UI already showing all loaded AND backend has more → call API
    if (visibleCount >= itemList.length && hasMore && !isLoadingMore) {
      onLoadMore(); // parent will append cards + update offset/hasMore
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0  bg-black/80 backdrop-blur-sm z-999999 flex items-center justify-center p-4">
      <div className="bg-(--color-naviBlue) relative box-shadow-custom w-full max-w-274.25 max-h-100 2xl:max-h-155 flex flex-col">
        <div className="flex flex-col gap-4 md:flex-row items-center justify-between px-6 py-3 md:py-5 2xl:py-8 border-b-4 border-[var(--color-gray)]">
          <h2 className="font-onest text-sm md:text-xl font-semibold text-white">
            Join game
          </h2>
          <div className="">
            <button
              onClick={onClose}
              className="absolute top-3 right-3 cursor-pointer"
            >
              <img
                src="/images/coinFlip/modal/cross.svg"
                className=" p-5"
                alt="cross"
              />
            </button>
          </div>
        </div>

        {/* Items Grid */}
        <div
          ref={scrollRef}
          onScroll={handleScroll}
          className="no-scrollbar flex-1 overflow-y-auto p-3"
        >
          {cardLoading ? (
            <div className=" flex w-full h-[260px] items-center justify-center">
              <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
            </div>
          ) : (
            <>
              {cardsError ? (
                <h1 className="text-center text-white text-sm md:text-2xl">
                  {cardsError}
                </h1>
              ) : (
                <>
                  {itemList.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-16 text-center">
                      <p className="text-base md:text-3xl font-bold text-white mb-2">
                        Open your packs to get started
                      </p>
                      <p className="text-sm md:text-2xl text-[var(--color-slate)] max-w-md">
                        Once you open a pack, your inventory cards will appear
                        here.
                      </p>
                    </div>
                  ) : (
                    <>
                      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-7 gap-4">
                        {itemList.slice(0, visibleCount).map((item, index) => (
                          <div
                            key={index}
                            onClick={() => toggleItemSelection(item.inv_id)}
                            className={`relative group bg-[#1F1C26] p-3 cursor-pointer transition-all border-[1.5] ${
                              item?.selected
                                ? "border-[var(--color-blue)] box-shadow-custom-inset"
                                : "border-[#1F1C26] "
                            }`}
                          >
                            {!item.selected && (
                              <div className="absolute group-hover:w-10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 left-1/2 -translate-x-1/2 w-5 h-5 h-5 group-hover:md:h-20 bg-[var(--color-blue)] group-hover:blur-xl transition-all duration-500 blur-3xl rounded-full opacity-50"></div>
                            )}
                            <div
                              className={` flex flex-col justify-center items-center transition-all duration-300`}
                            >
                              {/* Item Name */}
                              <div
                                className={` 
                        ${
                          !item.selected &&
                          "duration-300  group-hover:-translate-y-1"
                        }
                        text-center font-sofia mb-2`}
                              >
                                <h3 className="text-xs md:text-base` font-bold text-white uppercase italic tracking-wide">
                                  {item.name}
                                </h3>
                                <p className="text-[10px] md:text-xs text-[var(--color-slate)] uppercase mt-0.5">
                                  {item.rarity}
                                </p>
                              </div>

                              <div
                                className={`mb-1
                        ${
                          !item.selected &&
                          "duration-300  group-hover:-translate-y-1"
                        }
                        `}
                              >
                                <div className=" img-border-radius overflow-hidden">
                                  {/* Placeholder for actual card image */}
                                  <div className="w-15.2 h-22 flex items-center justify-center text-white/20 text-4xl font-bold">
                                    <img
                                      src={item.image.replace(
                                        "cardsimages",
                                        "cards/images",
                                      )}
                                      className="w-full h-full  object-contain "
                                      alt="item.image"
                                    />
                                  </div>
                                </div>
                                {item.selected && (
                                  <div className="absolute bottom-0 left-0 bg-[var(--color-blue)] shadow-lg p-2">
                                    <img
                                      src="/images/coinFlip/modal/tick.svg"
                                      alt="tick"
                                    />
                                  </div>
                                )}
                              </div>

                              {/* Price */}
                              <div
                                className={`
                         ${
                           !item.selected &&
                           "duration-300  group-hover:-translate-y-1"
                         }
                        text-center`}
                              >
                                <span className="text-sm flex items-center gap-1 font-bold text-(--color-blue)">
                                  {user?.activeMode === "coins" ? (
                                    <img
                                      src="/images/header/win.svg"
                                      alt="win"
                                      className="h-4 w-4"
                                    />
                                  ) : (
                                    <img
                                      src="/images/header/star.svg"
                                      alt="star"
                                      className="h-4 w-4"
                                    />
                                  )}{" "}
                                  {item.price}
                                </span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* ✅ lazy loading indicator */}
                      <div className="flex justify-center py-4">
                        {isLoadingMore ? (
                          <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                        ) : visibleCount < itemList.length ? (
                          <p className="text-xs text-white/70">
                            Scroll to load more…
                          </p>
                        ) : hasMore ? (
                          <p className="text-xs text-white/70">
                            Scroll to load more…
                          </p>
                        ) : (
                          <p className="text-xs text-white/40">
                            All items loaded
                          </p>
                        )}
                      </div>
                    </>
                  )}
                </>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-5 border-t-2 border-[var(--color-gray)]">
          <div className="flex items-center justify-between">
            <div className="flex items-center text-white gap-3 md:gap-12">
              <div className="flex gap-3 items-center">
                <div className="text-xs md:text-lg  uppercase tracking-wider font-semibold ">
                  ITEM VALUE
                </div>
                <div className="flex items-center gap-2 text-lg md:text-3xl font-extrabold text-[var(--color-blue)]">
                  {user?.activeMode === "coins" ? (
                    <img
                      src="/images/header/win.svg"
                      alt="coins"
                      className="h-4 w-4"
                    />
                  ) : (
                    <img
                      src="/images/header/star.svg"
                      alt="star"
                      className="h-4 w-4"
                    />
                  )}

                  {totalValue.toFixed(2)}
                </div>
              </div>
            </div>
            <button
              onClick={() => {
                const selectedItems = itemList.filter((item) => item.selected);

                const selectedCards: SelectedInvCard[] = selectedItems.map(
                  (item) => ({
                    inv_id: item.inv_id,
                    image: item.image,
                    price: item.price,
                    name: item.name,
                    rarity: item.rarity,
                  }),
                );

                onSelectedCardsChange?.(selectedCards);

                // ✅ ONLY inv_id array
                const cardsPayload = selectedItems.map((item) => item.inv_id);

                const totalPrice = selectedItems.reduce(
                  (sum, item) => sum + item.price,
                  0,
                );

                const socket = getSocket();
                socket.emit("joinGame", {
                  user_id: user?.userId,
                  cards: cardsPayload, // 👈 [inv_id, inv_id]
                  price: totalPrice,
                  image: user?.image || "", // user image
                });

                onClose();
              }}
              className={`px-3 md:px-10 cursor-pointer py-3 text-white font-onest md:text-base font-bold bg-[var(--color-blue)]  text-xs uppercase tracking-wide transition-all ${
                selectedCount === 0
                  ? "cursor-not-allowed pointer-events-none"
                  : " hover:bg-(--color-hoverBlue) text-white"
              }
              `}
              // ${joinLocked ? "opacity-50  cursor-not-allowed" : ""}
            >
              ADD CARD
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
