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

interface Item extends InventoryCard {
  selected?: boolean;
}
export const JoinGameModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  cards: InventoryCard[];
  xValue: string;
  cardLoading: boolean;
  cardsError: string | null;
  playCard: (card: any) => void;
  socket: ReturnType<typeof getSocket> | null;
  user: User | null;
  onLoadMore: () => Promise<void>;

  hasMore: boolean;
  isLoadingMore: boolean;
  betSubmittedRef: React.MutableRefObject<boolean>;
  
}> = ({
  isOpen,
  onClose,
  cards,
  xValue,
  playCard,
  cardLoading,
  cardsError,
  socket,
  user,
  onLoadMore,
  hasMore,
  isLoadingMore,
  betSubmittedRef,
}) => {
  const [itemList, setItemList] = useState<Item[]>([]);
  const [apiLoading, setApiLoading] = useState(false);

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

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

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

  // const selectedItems = itemList.filter((i) => i.selected);

  const payload = {
    userId: (user as any)?.userId || null,
    name: (user as any)?.name || "Player",
    balance: Number((user as any)?.balance || 0),
    image: (user as any)?.image || "/images/roll/profile.svg",

    xValue,
    cards: selectedItems.map((i) => ({
      inv_id: i.inv_id,
      price: i.price,
      image: i.image,
      name: i.name,
      rarity: i.rarity,
    })),
    totalValue,
    ts: Date.now(),
  };
  console.log("payload",payload)

  const truncate = (text: string, limit = 15) =>
    text.length > limit ? text.slice(0, limit) + "…" : text;

  // ✅ load more when near bottom
  const maybeLoadMore = () => {
    if (cardLoading) return;
    if (isFetchingMore) return;

    // already showing all
    if (visibleCount >= itemList.length) return;

    setIsFetchingMore(true);

    // small delay optional (feels smoother)
    window.setTimeout(() => {
      setVisibleCount((prev) => Math.min(prev + STEP, itemList.length));
      setIsFetchingMore(false);
    }, 150);
  };

  // const onScroll = () => {
  //   const el = scrollRef.current;
  //   if (!el) return;

  //   const threshold = 120; // px from bottom
  //   const reachedBottom =
  //     el.scrollTop + el.clientHeight >= el.scrollHeight - threshold;

  //   if (reachedBottom) maybeLoadMore();
  // };

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (cardLoading) return;

    const el = e.currentTarget;
    const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 120;
    if (!nearBottom) return;

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

    if (visibleCount >= itemList.length && hasMore && !apiLoading) {
      setApiLoading(true);
      Promise.resolve(onLoadMore()).finally(() => setApiLoading(false));
    }
  };

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

    setVisibleCount(STEP);
    setIsFetchingMore(false);

    setItemList((cards || []).map((c) => ({ ...c, selected: false })));

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

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

    setItemList((prev) => {
      const prevSelected = new Set(
        prev.filter((x) => x.selected).map((x) => x.inv_id),
      );
      return (cards || []).map((c) => ({
        ...c,
        selected: prevSelected.has(c.inv_id),
      }));
    });
  }, [cards, isOpen]);

  // attach scroll listener only when open

  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-[var(--color-naviBlue)] relative box-shadow-custom w-full max-w-[1097px] max-h-[450px] 2xl:max-h-[840px] flex flex-col">
        {/* Header */}
        <div className="flex flex-col gap-4 md:flex-row items-center justify-between px-6 py-3 md:py-3 2xl:py-5 border-b-4 border-[var(--color-gray)]">
          <div className="flex items-center gap-3">
            <img src="/images/roll/img5.svg" alt="" />
            <h2 className="font-sofia text-sm md:text-xl font-semibold text-white">
              Join game
            </h2>
          </div>
          <div className="flex items-center">
            <div className="flex items-center gap-6 md:mr-10">
              <span className="text-sm md:text-xl tracking-wide font-semibold font-sofia uppercase">
                {xValue.toLocaleLowerCase()} return
              </span>
            </div>

            <button
              onClick={() => {
                if (!betSubmittedRef.current) {
                  socket?.emit("cancelJoin");
                }
                setItemList(
                  (cards || []).map((c) => ({ ...c, selected: false })),
                );
                onClose();
              }}
              className="absolute top-3 md:top-6.5 right-0 md:right-4 cursor-pointer"
            >
              <img
                src="/images/coinFlip/modal/cross.svg"
                className="p-2"
                alt=""
              />
            </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>{cardsError}</h1>
              ) : (
                <>
                  {/* itemList */}
                  {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, ind) => (
                          <div
                            // bg-[#1F1C26]
                            key={item.inv_id}
                            onClick={() => toggleItemSelection(item.inv_id)}
                            className={`relative group bg-[var(--color-darkBlue)] duration-300 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-[150px] md:w-5 h-5 md:h-5 group-hover:md:h-20 bg-[var(--color-blue)] group-hover:blur-xl transition-all duration-300 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 &&
                                  "group-hover:-translate-y-1 duration-300"
                                }  text-center mb-2`}
                              >
                                <h3 className="text-xs md:text-base font-bold text-white uppercase italic tracking-wide">
                                  {truncate(item.name)}
                                </h3>
                                <p className="text-[10px] md:text-xs text-[var(--color-slate)] uppercase mt-0.5">
                                  {item.rarity}
                                </p>
                              </div>

                              {/* Item Image/Card */}
                              <div
                                className={`${
                                  !item.selected &&
                                  "group-hover:-translate-y-1 duration-300"
                                } mb-1`}
                              >
                                <div className=" img-border-radius overflow-hidden">
                                  {/* Placeholder for actual card image */}
                                  <div className="w-[62px] h-[88px] 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=""
                                    />
                                  </div>
                                </div>

                                {/* Selection Checkmark */}
                                {item.selected && (
                                  <div className="absolute bottom-0 left-0 bg-[var(--color-blue)] shadow-lg p-1">
                                    <img
                                      src="/images/coinFlip/modal/tick.svg"
                                      alt=""
                                    />
                                  </div>
                                )}
                              </div>

                              {/* Price */}
                              <div
                                className={`${
                                  !item.selected && "group-hover:-translate-y-1"
                                } text-center duration-300`}
                              >
                                <span className="text-sm flex items-center gap-2 font-bold text-[var(--color-blue)]">
                                  {user?.activeMode === "coins" ? (
                                    <img
                                      src="/images/header/win.svg"
                                      alt=""
                                      className="h-4 w-4"
                                    />
                                  ) : (
                                    <img
                                      src="/images/header/star.svg"
                                      alt=""
                                      className="h-4 w-4"
                                    />
                                  )}
                                  {item.price}
                                </span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                      {/* ✅ lazy loading indicator */}
                      <div className="flex justify-center py-4">
                        {apiLoading ? (
                          <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                        ) : 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 gap-3 md:gap-12">
              <div className="flex flex-col items-center">
                <div className="text-lg md:text-4xl font-extrabold text-[var(--color-blue)]">
                  ${totalValue.toFixed(2)}
                </div>
                <div className="text-xs md:text-base uppercase tracking-wider font-semibold ">
                  ITEM VALUE
                </div>
              </div>
              <div className="flex flex-col items-center">
                <div className="text-lg md:text-4xl font-extrabold text-[var(--color-blue)]">
                  {selectedCount.toString().padStart(2, "0")}
                </div>
                <div className="text-xs md:text-base uppercase tracking-wider font-semibold ">
                  TOTAL ITEMS
                </div>
              </div>
            </div>

            <button
              onClick={() => {
                betSubmittedRef.current = true;

                socket?.emit("placeBet", payload); // ✅ this matches your server handler
                console.log(payload);
                onClose();
                playCard(payload);
              }}
              disabled={selectedCount === 0}
              className="px-3 flex items-center cursor-pointer gap-4 md:px-10 py-1.5 font-onest bg-[#83A754] md:text-base font-bold text-xs uppercase tracking-wide transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <img src="/images/roll/img5.svg" className="w-8 h-8" alt="" />
              <span>PLAY GAME</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
