"use client";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import SortDropdown, { SortValue } from "../components/trade/SortDropdown";
import TradeCard from "../components/trade/TradeCard";
import { getTradeCards, TradeApiCard } from "../lib/api/trade";

type ChildTab = "magic" | "pokemon" | "lorcana";

type TradeCardItem = {
  id: number;
  player: string;
  timeAgo: string;
  rarity: string;
  name: string;
  price: string; // "$11.90"
  image: string;
  date?: number;
};

// 👇 brand sent to your API for each tab
const BRAND_BY_TAB: Record<ChildTab, string> = {
  magic: "Magic",
  pokemon: "Pokemon",
  lorcana: "Lorcana",
};

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { fetchInventoryCards, InventoryCard } from "../lib/api/inventory";
import { InventoryModal } from "../components/trade/InventoryModal";
import { getFullImageUrl } from "@/constants";
import TradingRagingView from "../components/trade/TradingRagingView";
import AlertModal from "../components/ui/AlertModal";
import NotAvailable from "../components/ui/NotAvailable";

interface AuthState {
  user: User; // adjust type as needed
  status: string;
}

const Inner = () => {
  const [childTab, setChildTab] = useState<ChildTab>("magic");
  const [invCards, setInvCards] = useState<InventoryCard[]>([]);
  const [offset, setOffset] = useState<number | null>(null);
  const [hasMoreInv, setHasMoreInv] = useState(true);
  const [isLoadingMoreInv, setIsLoadingMoreInv] = useState(false);
  const [isLoadingCards, setIsLoadingCards] = useState(false);
  const [cardsError, setCardsError] = useState<string | null>(null);
  const [hasLoadedCards, setHasLoadedCards] = useState(false);
  const [openInventory, setOpenInventory] = useState(false);
  const [showTradingRaging, setshowTradingRaging] = useState(false);
  const [selectedCard, setSelectedCard] = useState<TradeCardItem | null>(null);
  const [search, setSearch] = useState("");
  const [sort, setSort] = useState<SortValue>("price_desc");

  const [selectedInvCards, setSelectedInvCards] = useState<InventoryCard[]>([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  const [cardsByTab, setCardsByTab] = useState<
    Record<ChildTab, TradeCardItem[]>
  >({
    magic: [],
    pokemon: [],
    lorcana: [],
  });

  const [loadingByTab, setLoadingByTab] = useState<Record<ChildTab, boolean>>({
    magic: false,
    pokemon: false,
    lorcana: false,
  });

  const [errorByTab, setErrorByTab] = useState<Record<ChildTab, string | null>>(
    {
      magic: null,
      pokemon: null,
      lorcana: null,
    },
  );

  // ✅ cart
  const cards = cardsByTab[childTab];

  const formatTimeAgo = (unixSeconds: number): string => {
    const now = Date.now();
    const time = unixSeconds * 1000;
    const diffMs = now - time;

    if (diffMs < 0) return "JUST NOW";

    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    if (diffMinutes < 1) return "JUST NOW";
    if (diffMinutes < 60) return `${diffMinutes}MIN AGO`;

    const diffHours = Math.floor(diffMinutes / 60);
    if (diffHours < 24) return `${diffHours}HRS AGO`;

    const diffDays = Math.floor(diffHours / 24);
    return `${diffDays}DAYS AGO`;
  };

  const mapApiCardToTradeCardItem = (card: TradeApiCard): TradeCardItem => {
    const imgPath = card.image.startsWith("/") ? card.image : `/${card.image}`;

    return {
      id: card.id,
      player: card.user_name,
      date: Number(card.date) || 0,
      timeAgo: formatTimeAgo(Number(card.date) || 0),
      rarity: card.rarity?.toUpperCase() ?? "",
      name: card.name,
      price: `${Number(card.price).toFixed(2)}`,
      image: imgPath,
    };
  };

  // Inventory Cards Laoded
  const loadCards = async (userId: any, token: any) => {
    if (!user?.userId || !user?.token) return; // ✅ guard

    try {
      setIsLoadingCards(true);
      setCardsError(null);

      const data = await fetchInventoryCards(userId, "no", token);

      setInvCards(data.cards);
      setOffset(data.offset);
      setHasMoreInv(data.cards.length > 0);
      setHasLoadedCards(true);
    } catch (err: any) {
      console.error(err);
      const msg =
        err?.response?.data?.error ||
        err?.response?.data?.message ||
        err?.message;
      setCardsError(msg || "Failed to load cards");
    } finally {
      setIsLoadingCards(false);
    }
  };

const loadCardsHandler = () => {
  if (!user?.userId || !user?.token) return;
  loadCards(user.userId, user.token);
}

  const loadMoreInventory = async () => {
    if (!user?.userId || !user?.token) return;
    if (!hasMoreInv) return;
    if (isLoadingMoreInv) return;
    if (offset == null) return;

    try {
      setIsLoadingMoreInv(true);

      const data = await fetchInventoryCards(
        user.userId,
        "no",
        user.token,
        offset,
      );

      // 🔴 STOP CONDITION
      if (data.cards.length === 0) {
        setHasMoreInv(false); // ❌ no more requests
        setIsLoadingMoreInv(false);
        return;
      }

      setInvCards((prev) => [...prev, ...data.cards]); // ✅ append
      setOffset(data.offset ?? null); // ✅ next offset
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoadingMoreInv(false);
    }
  };

  const parsePrice = (p: string) => Number(String(p).replace("$", "")) || 0;

  const filteredSortedCards = React.useMemo(() => {
    const q = search.trim().toLowerCase();

    // filter
    const filtered = cards.filter((c) => {
      if (!q) return true;
      return (
        c.name?.toLowerCase()?.includes(q) ||
        c.rarity?.toLowerCase()?.includes(q) ||
        c.player?.toLowerCase()?.includes(q)
      );
    });

    // sort
    const sorted = [...filtered].sort((a, b) => {
      if (sort === "price_desc")
        return parsePrice(b.price) - parsePrice(a.price);
      if (sort === "price_asc")
        return parsePrice(a.price) - parsePrice(b.price);
      if (sort === "date_newest") return (b.date ?? 0) - (a.date ?? 0);
      if (sort === "date_oldest") return (a.date ?? 0) - (b.date ?? 0);

      if (sort === "name_az") return (a.name || "").localeCompare(b.name || "");
      if (sort === "name_za") return (b.name || "").localeCompare(a.name || "");

      return 0;
    });

    return sorted;
  }, [cards, search, sort]);

  const handleConfirmInventoryCards = (cards: InventoryCard[]) => {
    setSelectedInvCards(cards);
    setOpenInventory(false);
  };

  const handleAddToCart = (card: TradeCardItem) => {
    // if(!user) return;
    setshowTradingRaging(true);
    setSelectedCard(card);
  };

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

  const load = async (force = false) => {
    console.log("called");
    // already loaded? do nothing
    if (!force && cardsByTab[childTab].length > 0) return;

    const brand = BRAND_BY_TAB[childTab];

    setLoadingByTab((prev) => ({ ...prev, [childTab]: true }));
    setErrorByTab((prev) => ({ ...prev, [childTab]: null }));

    try {
      const data = await getTradeCards(brand);
      const mapped = data.cards.map(mapApiCardToTradeCardItem);

      setCardsByTab((prev) => ({
        ...prev,
        [childTab]: mapped,
      }));
    } catch (err: any) {
      setErrorByTab((prev) => ({
        ...prev,
        [childTab]: err?.message || "Failed to load cards",
      }));
    } finally {
      setLoadingByTab((prev) => ({ ...prev, [childTab]: false }));
    }
  };

  // ✅ load each tab's data only once (no infinite calls)
  useEffect(() => {
    load();
  }, [childTab, user?.userId, user?.token]); // ✅ deps important

  // ✅ remove single inventory card
  const handleRemoveInvCard = (cardId: number) => {
    setSelectedInvCards((prev) => prev.filter((c) => c.inv_id !== cardId));
  };

  const isLoading = loadingByTab[childTab];
  const error = errorByTab[childTab];
  const noResults =
    !isLoading && filteredSortedCards.length === 0 && search.trim().length > 0;

  return (
    <div className="min-h-screen bg-black text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <div
          className={`
          pb-10
        `}
        >
          <div className="container mx-auto md:px-0 md:py-2">
            <>
              {showTradingRaging ? (
                <TradingRagingView
                  selectedCard={selectedCard}
                  setSelectedCard={setSelectedCard}
                  setshowTradingRaging={setshowTradingRaging}
                  setOpenInventory={setOpenInventory}
                  getFullImageUrl={getFullImageUrl}
                  selectedInvCards={selectedInvCards}
                  setSelectedInvCards={setSelectedInvCards}
                  onRemoveInvCard={handleRemoveInvCard}
                  userId={user.userId}
                  token={user.token}
                  loadTradeCards={load}
                  loadCards={loadCardsHandler}
                />
              ) : (
                <div>
                  <div className="">
                    <div className="flex items-center flex-col mb-3 md:flex-row mt-4 justify-between gap-4">
                      <div className="flex flex-wrap gap-2 flex-col md:flex-row 2xl:gap-4">
                        <input
                          type="text"
                          placeholder="SEARCH ITEMS"
                          value={search}
                          onChange={(e) => setSearch(e.target.value)}
                          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-62.5 outline-none focus:outline-none focus:ring-0"
                        />

                        {/* Tabs */}
                        <button
                          onClick={() => setChildTab("magic")}
                          className={`px-4 md:px-6 py-1 md:py-2 font-extrabold transition-all text-xs 2xl:text-lg bg-(--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-(--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")}
                          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")}
                          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>
                      </div>

                      <SortDropdown value={sort} onChange={setSort} />
                    </div>
                  </div>

                  {/* Main content + Cart */}
                  <div className="container mx-auto px-4 md:px-0 pb-10  flex gap-6">
                    <div className="transition-all duration-300 w-full">
                      {error && (
                        <div className="mb-4 text-center text-(--color-red) text-sm">
                          {error ===
                          "Cannot read properties of null (reading 'userId')"
                            ? "User Not Found "
                            : error}
                        </div>
                      )}
                      <AlertModal
                        open={modalOpen}
                        type={modalType}
                        message={modalMsg}
                        onClose={() => setModalOpen(false)}
                      />

                      {isLoading && cards.length === 0 ? (
                        <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>
                      ) : (
                        <>
                          <div
                            className="
  mt-1 grid gap-3
  grid-cols-[repeat(auto-fill,minmax(140px,1fr))]
  md:grid-cols-[repeat(auto-fill,minmax(160px,1fr))]
  lg:grid-cols-[repeat(auto-fill,minmax(180px,1fr))]
"
                          >
                            {!noResults && (
                              <>
                                {filteredSortedCards.length === 0 ? (
                                  <div className="col-span-full text-center py-20 text-[var(--color-slate)]">
                                    <p className="text-xl md:text-3xl font-bold">
                                      No data found
                                    </p>
                                    <p className="text-sm md:text-xl mt-1">
                                      Try changing the tab, search, or sort
                                    </p>
                                  </div>
                                ) : (
                                  filteredSortedCards.map((card) => (
                                    <TradeCard
                                      key={card.id}
                                      card={card}
                                      onClick={() => {
                                        if (!user) {
                                          setModalType("error");
                                          setModalMsg(
                                            "You must be logged in to trade.",
                                          );
                                          setModalOpen(true);
                                          return;
                                        }
                                        handleAddToCart(card);
                                      }}
                                    />
                                  ))
                                )}
                              </>
                            )}
                          </div>
                        </>
                      )}
                    </div>

                    {/* <div className="absolute left-0 right-0 bottom-0 bg-black min-h-20 2xl:min-h-[150px] w-full"> */}

                    {/* </div> */}
                  </div>
                </div>
              )}
            </>

            <InventoryModal
              offset={offset ?? null}
              user={user}
              cards={invCards}
              isOpen={openInventory}
              onClose={() => setOpenInventory(false)}
              cardLoading={isLoadingCards}
              cardsError={cardsError}
              onConfirm={handleConfirmInventoryCards}
              initialSelectedIds={selectedInvCards.map((c) => c.inv_id)}
              onLoadMore={loadMoreInventory}
              hasMore={hasMoreInv}
              isLoadingMore={isLoadingMoreInv}
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default Inner;
