import { InventoryCard } from "@/app/lib/api/inventory";
import { AuthState } from "@/app/wallet/page";
import { User } from "@/constants/types";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";

interface Item {
  inv_id: number;
  id: number;
  name: string;
  rarity: string;
  price: number;
  image: string;
  selected: boolean;
}

export const JoinGameModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
  user: User | null;
  cardLoading: boolean;
  cardsError: string | null;
  cards: InventoryCard[] | null;

  onConfirm: (cards: InventoryCard[]) => void | Promise<void>;

  onAddItems?: (cards: InventoryCard[]) => Promise<void> | void;

  initialSelectedIds?: string[]; // ✅ optional

  minJoinAmount?: number; // ✅ NEW
  isCreateFlow?: boolean; // ✅ NEW (optional)

  offset: number | null;
  onLoadMore: () => void;
  hasMore: boolean;
  isLoadingMore: boolean;
}> = ({
  isOpen,
  onClose,
  cards,
  cardLoading,
  cardsError,
  onConfirm,
  minJoinAmount,
  isCreateFlow,
  initialSelectedIds = [],
  onAddItems,
  offset,
  onLoadMore,
  hasMore,
  isLoadingMore,
}) => {
  const [itemList, setItemList] = useState<Item[]>([]);
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

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

  const selectedCards = itemList.filter((i) => i.selected);
  const totalValue = selectedCards.reduce(
    (sum, i) => sum + (Number(i.price) || 0),
    0,
  );

  const minAllowed = !isCreateFlow && minRequired > 0 ? minRequired * 0.9 : 0;
  const maxAllowed = !isCreateFlow && minRequired > 0 ? minRequired * 1.1 : 0;

  const isOutOfRange =
    !isCreateFlow &&
    minRequired > 0 &&
    (totalValue < minAllowed || totalValue > maxAllowed);

  // const isBelowMin =
  //   !isCreateFlow && minRequired > 0 && totalValue < minRequired;

  const toggleItemSelection = (id: number) => {
    setItemList((prevItems) =>
      prevItems.map((item) =>
        item.inv_id === id ? { ...item, selected: !item.selected } : item,
      ),
    );
  };
  // const selectedCards = itemList.filter((i) => i.selected);
  const selectedCount = selectedCards.length;

  // ✅ items to show right now
  const visibleItems = useMemo(
    () => itemList.slice(0, visibleCount),
    [itemList, visibleCount],
  );

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

    setVisibleCount(STEP);
    setIsFetchingMore(false);

    // Reset list on open, apply initialSelectedIds once
    setItemList(
      (cards || []).map((c: any) => ({
        ...c,
        selected: initialSelectedIds.includes(String(c.inv_id)), // ✅ string match
      })),
    );

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

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

    setItemList((prev) => {
      const selectedMap = new Map<number, boolean>();
      prev.forEach((p) => selectedMap.set(p.inv_id, p.selected));

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

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

    if (!nearBottom) return;

    // pehle UI visibleCount badhao (optional)
    if (!isFetchingMore && visibleCount < itemList.length) {
      setIsFetchingMore(true);
      setTimeout(() => {
        setVisibleCount((c) => Math.min(c + STEP, itemList.length));
        setIsFetchingMore(false);
      }, 250);
      return;
    }

    // ✅ agar UI me sab items already visible hain
    // aur server pe abhi "more" hai, to API next page hit karo
    if (
      nearBottom &&
      visibleCount >= itemList.length &&
      hasMore &&
      !isLoadingMore
    ) {
      onLoadMore();
    }
  };

  const handleAdd = async () => {
    const selectedCards = itemList.filter((i) => i.selected);
    if (selectedCards.length === 0) return;

    // ✅ JOIN FLOW ±10% range check
    if (!isCreateFlow && minRequired > 0) {
      if (totalValue < minAllowed || totalValue > maxAllowed) {
        setErrorMsg(
          `You can only join between $${minAllowed.toFixed(
            2,
          )} and $${maxAllowed.toFixed(2)}`,
        );
        return;
      }
    }

    setErrorMsg(null);

    // ✅ JOIN FLOW (existing behavior)
    await onConfirm(selectedCards as any);
    onClose();
  };

  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">
        {/* Header */}
        <div className="flex flex-col gap-4 md:flex-row items-center justify-between px-6 pr-14 py-3 md:py-5 2xl:py-8 border-b-4 border-(--color-gray)">
          <h2 className="font-onest text-sm md:text-xl font-semibold text-white">
            Join game
          </h2>
          {errorMsg && (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
              <div className="relative w-full max-w-lg border mx-4 md:mx-0 border-(--color-gray) bg-(--color-naviBlue) px-3 md:px-6 py-4 text-red-100 shadow-xl">
                {/* Header */}
                <div className="mb-1  flex items-center justify-end">
                  <button
                    onClick={() => setErrorMsg(null)}
                    className="rounded-md cursor-pointer text-xl hover:scale-115 font-onest px-2 text-white hover:text-white"
                    aria-label="Close error"
                  >
                    <img src="/images/ui/cross.svg" alt="" />
                  </button>
                </div>

                {/* Message */}
                <p className="text-xl pt-5 md:text-text-4xl text-center font-onest leading-relaxed text-white">
                  {errorMsg}
                </p>
              </div>
            </div>
          )}

          <div className="">
            {/* {selectedCount ? (
              <span className="text-sm md:text-xl md:mr-5 font-bold text-[#F14B3F]">
                NEEDS $1000-$1100
              </span>
            ) : (
              <div className="flex items-center gap-6 md:mr-5">
                <span className="text-sm md:text-xl font-bold font-onest tracking-tighter">
                  Minimum: $10
                </span>
                <span className="text-sm md:text-xl font-bold font-onest tracking-tighter">
                  Max. Items: 20 Items
                </span>
              </div>
            )} */}

            <button
              onClick={onClose}
              className="absolute top-4 right-4 md:top-0 md:right-0 cursor-pointer"
            >
              <img
                src="/images/coinFlip/modal/cross.svg"
                className=" md:p-5"
                alt=""
              />
            </button>
          </div>
          {/* ✅ Error message */}
        </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-65 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>
          ) : (
            <>
              {visibleItems.length < 1 ? (
                <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">
                    {visibleItems.map((item, ind) => (
                      <div
                        key={ind}
                        onClick={() => toggleItemSelection(item.inv_id)}
                        className={`relative group bg-[#1F1C26] p-3 cursor-pointer transition-all border-[1.5] ${
                          item.selected
                            ? "border-(--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 w-37.5 md:w-5 h-5 md:h-5 group-hover:md:h-20 bg-(--color-blue) group-hover:blur-xl transition-all duration-500 blur-3xl rounded-full opacity-50"></div>
                        )}
                        <div
                          className={`${
                            !item.selected && "group-hover:-translate-y-1"
                          } flex flex-col justify-center items-center transition-all duration-300`}
                        >
                          {/* Item Name */}
                          <div className="text-center mb-2">
                            <h3 className="text-xs md:text-base font-bold text-white uppercase italic tracking-wide">
                              {item.name.length > 15
                                ? item.name.slice(0, 15) + "…"
                                : item.name}
                            </h3>
                            <p className="text-[10px] md:text-xs text-(--color-slate) uppercase mt-0.5">
                              {item.rarity}
                            </p>
                          </div>

                          {/* Item Image/Card */}
                          <div className=" mb-1">
                            <div className="rounded-lg shadow-md overflow-hidden">
                              {/* Placeholder for actual card image */}
                              <div className="w-15.5 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=""
                                />
                              </div>
                            </div>

                            {/* Selection Checkmark */}
                          </div>

                          {/* Price */}
                          <div className="text-center">
                            <span className="text-sm flex items-center gap-1 font-bold text-(--color-blue)">
                              {!user ? (
                                <img
                                  src="/images/header/win.svg"
                                  alt=""
                                  className="h-4 w-4"
                                />
                              ) : (
                                <>
                                  {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>
                        {item.selected && (
                          <div className="absolute bottom-0 left-0 bg-(--color-blue) shadow-lg p-1">
                            <img
                              src="/images/coinFlip/modal/tick.svg"
                              className="w-3"
                              alt=""
                            />
                          </div>
                        )}
                      </div>
                    ))}
                  </div>

                  {hasMore ? (
                    isLoadingMore ? (
                      <div className="flex justify-center py-4">
                        <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                      </div>
                    ) : (
                      <p className="text-xs text-white/70 text-center py-4">
                        Scroll to load more…
                      </p>
                    )
                  ) : (
                    <h1 className="mt-2 text-sm md:text-lg text-center text-white/40">
                      All items loaded
                    </h1>
                  )}
                </>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-5 border-t-2 border-(--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-(--color-blue)">
                  ${totalValue.toFixed(2)}
                </div>
                <div className="text-xs uppercase tracking-wider font-semibold md:mt-1">
                  ITEM VALUE
                </div>
              </div>
              <div className="flex flex-col items-center">
                <div className="text-lg md:text-4xl font-extrabold text-(--color-blue)">
                  {selectedCount.toString().padStart(2, "0")}
                </div>
                <div className="text-xs uppercase tracking-wider font-semibold md:mt-1">
                  TOTAL ITEMS
                </div>
              </div>
            </div>
            {/* selectedCount === 0 || totalValue < 1000 || totalValue > 1100 */}
            <button
              disabled={selectedCount === 0}
              onClick={handleAdd}
              className={`px-3 md:px-10 py-3 cursor-pointer font-onest md:text-base font-bold text-xs uppercase tracking-wide transition-all ${
                selectedCount === 0
                  ? "bg-(--color-naturalGray) text-gray-500 cursor-not-allowed"
                  : "bg-(--color-blue) hover:bg-(--color-naviBlue) duration-300 border border-transparent hover:border-(--color-naturalGray) hover:from-gray-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl"
              }`}
            >
              ADD {selectedCount} {selectedCount === 1 ? "ITEM" : " ITEMS"}
              {/* ADD ${totalValue > 0 ? totalValue.toFixed(0) : "1000"} ITEMS */}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
