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

type ChildTab = "magic" | "pokemon" | "lorcana";
type CartItem = TradeCardItem & { tab: ChildTab };

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

// 👇 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";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}

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,
    timeAgo: formatTimeAgo(card.date),
    rarity: card.rarity?.toUpperCase() ?? "",
    name: card.name,
    price: `$${Number(card.price).toFixed(2)}`,
    image: imgPath,
  };
};

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

  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 [cartItems, setCartItems] = useState<CartItem[]>([]);
  const cards = cardsByTab[childTab];

  // ✅ load each tab's data only once (no infinite calls)
  useEffect(() => {
    const load = async () => {
      // already loaded? do nothing
      if (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();
    // 👇 only run when tab changes (prevents repeated API calls)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [childTab]);

  const handleAddToCart = (card: TradeCardItem) => {
    setCardsByTab((prev) => ({
      ...prev,
      [childTab]: prev[childTab].filter((c) => c.id !== card.id),
    }));

    setCartItems((prev) => [...prev, { ...card, tab: childTab }]);
    setCartOpen(true);
  };

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

    setCardsByTab((prev) => ({
      ...prev,
      [item.tab]: [...prev[item.tab], item],
    }));

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

  const totalItems = cartItems.length;
  const totalCost = cartItems.reduce((sum, item) => {
    const num = parseFloat(item.price.replace("$", ""));
    return sum + (isNaN(num) ? 0 : num);
  }, 0);

  const isLoading = loadingByTab[childTab];
  const error = errorByTab[childTab];

  return (
    <div className="min-h-screen bg-[var(--color-black)] text-white">
      <div
        className={`
          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">
            <div className="flex items-center justify-between">
              <div className="flex 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 ">
                  TRADE
                </h1>
              </div>
              <div className="font-sofia font-bold text-base md:text-xl 2xl:text-2xl py-1 hover:bg-[var(--color-gray)] duration-300 md:py-2 border border-[var(--color-blue)] bg-[var(--color-naviBlue)]  px-4 md:px-36">
                LIST ITEMS
              </div>
            </div>

            <div className="flex items-center flex-col 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"
                  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"
                />

                {/* 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-[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")}
                  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 /> */}
            </div>
          </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-[var(--color-red)] text-sm">
                {error}
              </div>
            )}

            {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-2 md:grid-cols-3 lg:grid-cols-5 2xl:grid-cols-6">
              {cards.map((card) => (
                <TradeCard
                  key={card.id}
                  card={card}
                  onClick={() => handleAddToCart(card)}
                />
              ))}
            </div>
          </div>

          <CartSidebar
            items={cartItems}
            handler={handleReturnFromCart}
            totalItems={totalItems}
            totalCost={totalCost}
            open={cartOpen}
            onClose={() => setCartOpen(false)}
            brand="Pokemon" // or derive from active tab
          />
        </div>
      </div>
    </div>
  );
};

export default Inner;
