"use client";
import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { IMAGE_BASE } from "./../../constants";

import ListCard, {
  TradeCardItem as InventoryCard,
  InventoryBrand,
} from "../components/list/ListCard";

import CartSidebar, {
  CartItem,
  // ChildTab,
} from "../components/list/CartSidebar";

import { fetchInventoryCards } from "../lib/api/inventory";
import TradeListingCard from "../components/list/TradeListingCard";
import { User } from "@/constants/types";
import { useSelector } from "react-redux";
type CardBrandTab = "magic" | "pokemon" | "lorcana";
type ChildTab = CardBrandTab | "listing";
const BRAND_BY_TAB: Record<CardBrandTab, InventoryBrand> = {
  magic: "MTG",
  pokemon: "Pokemon",
  lorcana: "Lorcana",
};

const getFullImageUrl = (img: string) => {
  if (!img) return "/placeholder.png";
  if (img.startsWith("http")) return img;
  return `${IMAGE_BASE}/${img.replace(/^\//, "")}`;
};

const Inner = () => {
  const [childTab, setChildTab] = useState<ChildTab>("magic");
  const [cartOpen, setCartOpen] = useState(false);

  const [selectedCardIds, setSelectedCardIds] = useState<number[]>([]);
  const [isLoadingCards, setIsLoadingCards] = useState(false);
  const [cardsError, setCardsError] = useState<string | null>(null);
  const [allCards, setAllCards] = useState<InventoryCard[]>([]);
  const [hasLoadedCards, setHasLoadedCards] = useState(false);

  // how many cards visible for infinite scroll
  const [visibleCount, setVisibleCount] = useState(20);
  const listingRefreshRef = useRef<() => void>(() => {});
  const [listingReloadToken, setListingReloadToken] = useState(0);
  const user = useSelector((state: any) => state.auth.user) as User | null;
  const status = useSelector((state: any) => state.auth.status);
  const loadCards = async (uid: any, tok: any) => {
    try {
      setIsLoadingCards(true);
      setCardsError(null);

      const data = (await fetchInventoryCards(uid, "yes", tok)).cards;
      const fixed = data.map((card) => ({
        ...card,
        image: getFullImageUrl(card.image),
      }));

      setAllCards(fixed);
      setHasLoadedCards(true);
    } catch (err: any) {
      console.error(err);
      setCardsError(err.message ?? "Failed to load cards");
    } finally {
      setIsLoadingCards(false);
    }
  };

  useEffect(() => {
    if (!hasLoadedCards) {
      if (!user) return;
      loadCards(user.userId, user.token);
    }
  }, [hasLoadedCards]);

  useEffect(() => {
    setVisibleCount(20);
  }, [childTab, allCards.length]);

  // const inventoryForTab = allCards.filter(
  //   (card) => card.brand === BRAND_BY_TAB[childTab]
  // );
  const inventoryForTab =
    childTab === "listing"
      ? []
      : allCards.filter((card) => card.brand === BRAND_BY_TAB[childTab]);

  const cardsToShow = inventoryForTab.slice(0, visibleCount);

  useEffect(() => {
    const handleScroll = () => {
      if (
        window.innerHeight + window.scrollY >=
        document.body.offsetHeight - 300
      ) {
        setVisibleCount((prev) => {
          const total = inventoryForTab.length;
          if (prev >= total) return prev;
          return Math.min(prev + 20, total);
        });
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [inventoryForTab.length]);

  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const clearCart = () => {
    setCartItems([]);
  };
  const handleListingCardClick = (card: {
    id: number;
    player: string;
    timeAgo: string;
    rarity: string;
    name: string;
    price: string;
    image: string;
  }) => {
    const cartItem: CartItem = {
      id: card.id,
      player: card.player || "YOU",
      timeAgo: card.timeAgo || "",
      rarity: card.rarity,
      name: card.name,
      price: card.price,
      image: getFullImageUrl(card.image),
      brand: "Pokemon", // TODO: replace with real brand if you have it
      tab: "listing",
    };

    setCartItems([cartItem]); // sirf ye card sidebar me dikhana
    setCartOpen(true);
  };

  const handleAddToCart = (card: InventoryCard) => {
    const cartItem: CartItem = {
      id: card.inv_id,
      player: "YOU",
      timeAgo: "",
      rarity: card.rarity,
      name: card.name,
      price: `$${Number(card.price).toFixed(2)}`,
      image: card.image,
      inventory: card.count ?? 0,
      brand: card.brand, // ⬅️ yahan se milega
      tab: childTab,
    };

    setCartItems((prev) => {
      const exists = prev.some(
        (c) => c.id === cartItem.id && c.tab === cartItem.tab
      );

      if (exists) {
        return prev.filter(
          (c) => !(c.id === cartItem.id && c.tab === cartItem.tab)
        );
      } else {
        return [...prev, cartItem];
      }
    });

    setCartOpen(true);
  };

  const handleSelectCard = (card: InventoryCard) => {
    setSelectedCardIds((prev) => {
      if (prev.includes(card.inv_id)) {
        return prev.filter((id) => id !== card.inv_id);
      }
      return [...prev, card.inv_id];
    });

    handleAddToCart(card);
  };

  const handleReturnFromCart = (item: CartItem) => {
    setCartItems((prev) =>
      prev.filter((c) => !(c.id === item.id && c.tab === item.tab))
    );
    setSelectedCardIds((prev) => prev.filter((id) => id !== item.id));

    if (cartItems.length === 1) {
      setCartOpen(false);
    }
  };

  const totalItems = cartItems.length;
  const totalCost = cartItems.reduce((sum, item) => {
    const num = Number(
      item.price.trim().startsWith("$")
        ? item.price.trim().slice(1)
        : item.price.trim()
    );
    return sum + (isNaN(num) ? 0 : num);
  }, 0);
  const handlePriceChange = (item: CartItem, newPrice: number) => {
    // Update price in cart so UI reflects new value
    setCartItems((prev) =>
      prev.map((c) =>
        c.id === item.id && c.tab === item.tab
          ? { ...c, price: `$${newPrice.toFixed(2)}` }
          : c
      )
    );

    // 🔥 Trigger reload of TradeListingCard if we're on listing tab
    setListingReloadToken((prev) => prev + 1);
  };

  return (
    <div className="min-h-screen bg-[var(--color-black)] text-white">
      <div
        className={`
          md:px-4 pb-10 gap-6
          transition-all duration-500 ease-in-out
          ${cartOpen ? "md:w-[calc(100%-276px)]" : "w-full"}
        `}
      >
        <div className="z-10">
          <div className="container mx-auto px-4 md:px-0 md:py-2 md:mt-3">
            <h1 className="font-medium font-onest font-xs md:font-sm text-[#29313D] my-3 cursor-pointer">
              Trade &gt; List
            </h1>
            <div className="flex items-center justify-between">
              <div className="flex mb-2 items-center gap-4">
                <button className="cursor-pointer text-xs md:text-sm p-2 px-4 font-extrabold text-white bg-[var(--color-gray)] hover:text-white italic font-sofia transition">
                  &lt; BACK
                </button>
                <h1 className="text-sm md:text-2xl font-extrabold italic ">
                  LIST CARD
                </h1>
              </div>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-2 2xl:gap-4">
              <input
                type="text"
                placeholder="SEARCH ITEMS"
                className="text-[#DBFAFF] py-1 md:py-2  text-base md:text-lg 2xl:text-2xl font-sofia border border-[#29313D] px-5 md:min-w-[250px] outline-none focus:outline-none focus:ring-0"
              />
              <div className="flex my-1 md:my-0 gap-2">
                <button
                  onClick={() => {
                    if (childTab === "listing") {
                      clearCart?.();
                    }
                    setChildTab("magic");
                  }}
                  className={`px-4 md:px-6 py-1 md:py-2 font-extrabold transition-all text-xs 2xl:text-lg bg-[var(--color-naviBlue)] border-b-[3px] font-sofia border-transparent duration-500 md:text-base ${
                    childTab === "magic"
                      ? " text-white !border-[var(--color-blue)]"
                      : "text-[var(--color-slate)]  border-transparent cursor-pointer hover:opacity-100 hover:bg-[var(--color-gray)] opacity-60"
                  }`}
                >
                  <span className="flex items-center gap-2">
                    <Image
                      width={117}
                      height={37}
                      src="/images/inventory/magic.svg"
                      alt="magic"
                      className="w-12 md:w-full"
                    />
                  </span>
                </button>

                <button
                  onClick={() => {
                    setChildTab("pokemon");
                    if (childTab === "listing") {
                      clearCart?.();
                    }
                  }}
                  className={`px-4 md:px-6 py-1 md:py-2 font-extrabold transition-all text-xs 2xl:text-lg bg-[var(--color-naviBlue)] border-b-[3px] font-sofia border-transparent duration-500 md:text-base ${
                    childTab === "pokemon"
                      ? " text-white !border-[var(--color-blue)]"
                      : "text-[var(--color-slate)]  border-transparent cursor-pointer hover:opacity-100 hover:bg-[var(--color-gray)] opacity-60"
                  }`}
                >
                  <Image
                    width={117}
                    height={37}
                    src="/images/inventory/pokemon.svg"
                    alt="pokemon"
                    className="w-12 md:w-full"
                  />
                </button>

                <button
                  onClick={() => {
                    setChildTab("lorcana");
                    if (childTab === "listing") {
                      clearCart?.();
                    }
                  }}
                  className={`px-4 md:px-6 py-1 md:py-2 font-extrabold transition-all text-xs 2xl:text-lg bg-[var(--color-naviBlue)] border-b-[3px] font-sofia border-transparent duration-500 md:text-base ${
                    childTab === "lorcana"
                      ? " text-white !border-[var(--color-blue)]"
                      : "text-[var(--color-slate)]  border-transparent cursor-pointer hover:opacity-100 hover:bg-[var(--color-gray)] opacity-60"
                  }`}
                >
                  <Image
                    width={117}
                    height={37}
                    src="/images/inventory/lorcana.svg"
                    alt="lorcana"
                    className="w-12 md:w-full"
                  />
                </button>
                <button
                  onClick={() => {
                    setChildTab("listing");
                    if (["lorcana", "pokemon", "magic"].includes(childTab)) {
                      setSelectedCardIds([]); // 🔹 deselect all items
                      clearCart?.();
                    }
                  }}
                  className={`px-4 md:px-6 py-1 md:py-2 font-extrabold transition-all text-xs 2xl:text-lg bg-[var(--color-naviBlue)] border-b-[3px] font-sofia border-transparent duration-500 md:text-base ${
                    childTab === "listing"
                      ? " text-white !border-[var(--color-blue)]"
                      : "text-[var(--color-slate)]  border-transparent cursor-pointer hover:opacity-100 hover:bg-[var(--color-gray)] opacity-60"
                  }`}
                >
                  Listing
                </button>
              </div>
            </div>

            {cardsError && (
              <p className="mt-2 text-xs text-red-400">{cardsError}</p>
            )}
          </div>
        </div>

        <div className="container mx-auto px-4 md:px-0 pb-10 flex gap-6">
          {childTab === "listing" ? (
            // 🔹 LISTING TAB CONTENT
            <div className="transition-all duration-300 w-full">
              <TradeListingCard
                onCardClick={handleListingCardClick}
                reloadToken={listingReloadToken} // 🔥 watch this in TradeListingCard
              />
            </div>
          ) : isLoadingCards ? (
            // 🔹 LOADER FOR NORMAL TABS
            <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>
          ) : (
            // 🔹 NORMAL TABS GRID
            <div className="transition-all duration-300 w-full">
              <div className="mt-1 grid gap-3 grid-cols-2 md:grid-cols-3 lg:grid-cols-5 2xl:grid-cols-6">
                {cardsToShow.map((card) => (
                  <ListCard
                    key={card.inv_id}
                    card={card}
                    onClick={() => handleSelectCard(card)}
                    isSelected={selectedCardIds.includes(card.inv_id)}
                  />
                ))}
              </div>
            </div>
          )}

          <CartSidebar
            items={cartItems}
            handler={handleReturnFromCart}
            totalItems={totalItems}
            totalCost={totalCost}
            open={cartOpen}
            onClose={() => setCartOpen(false)}
            loadCardsHandler={() => {
              if (!user) return;
              loadCards(user.userId, user.token);
            }}
            onList={(item, qty) => {
              console.log("List this card", item.name, "with qty", qty);
            }}
            onClearCart={clearCart}
            showListButton={childTab !== "listing"}
            showEditBitton={childTab === "listing"}
            onPriceChange={handlePriceChange} // ⬅️ IMPORTANT
          />
        </div>
      </div>
    </div>
  );
};

export default Inner;
