import React, { useEffect, useState } from "react";
import Image from "next/image";
import { getFullImageUrl } from "@/constants";
import { buyOneTrade } from "@/app/lib/api/trade";

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

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

export type CartItem = TradeCardItem & { tab: ChildTab };

import { useSelector } from "react-redux";
import {User} from "@/constants/types";
interface AuthState {
  user: User;   // adjust type as needed
  status : string
}

type CartSidebarProps = {
  items: CartItem[];
  handler: (item: CartItem) => void;
  totalItems: number;
  totalCost: number;
  open: boolean; // controls slide-in
  onClose: () => void; // close button
  brand: string; // 🔹 NEW (e.g. "Pokemon")
};

// Local type with animation class
type AnimatedCartItem = CartItem & {
  animationClass?: string;
};

const CartSidebar = ({
  items,
  handler,
  totalItems,
  totalCost,
  open,
  onClose,
  brand
}: CartSidebarProps) => {
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  const [renderedItems, setRenderedItems] = useState<AnimatedCartItem[]>([]);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [resultOpen, setResultOpen] = useState(false);
  const [resultType, setResultType] = useState<"success" | "error" | null>(
    null
  );
  const [resultMsg, setResultMsg] = useState("");
  const [isBuying, setIsBuying] = useState(false);
const handleConfirmBuy = async () => {
  if (!items.length) return;

  try {
    setIsBuying(true);

    const payload = {
      user_id: user.userId,
      cards: items.map((i) => i.id),
      brand,
      action: "buy-trade" as const,
    };

    const res = await buyOneTrade(user.userId, 0, payload.cards,  user.token);

    if (res.resp === "success") {
      setResultType("success");
      setResultMsg(res.message || "Cards added to inventory successfully.");
    } else {
      setResultType("error");
      setResultMsg(res.message || "Failed to add cards to inventory.");
    }
  } catch (err) {
    console.error("buy-trade failed", err);
    setResultType("error");
    setResultMsg("Something went wrong while buying these cards.");
  } finally {
    setIsBuying(false);
    setConfirmOpen(false);
    setResultOpen(true);
  }
};

  useEffect(() => {
    setRenderedItems((prev) => {
      const next: AnimatedCartItem[] = [];
      const newIds = new Set(items.map((i) => i.id));

      // Handle items that are in the new `items` array
      items.forEach((item) => {
        const existing = prev.find((p) => p.id === item.id);

        if (existing) {
          // Keep existing animation state
          next.push({ ...item, animationClass: existing.animationClass });
        } else {
          // New item → fade-in
          next.push({ ...item, animationClass: "cart-item-enter" });
        }
      });

      // Handle removed items (present in prev, not in items)
      prev.forEach((oldItem) => {
        if (!newIds.has(oldItem.id)) {
          // If it's not already exiting, mark as exiting and keep it temporarily
          if (oldItem.animationClass !== "cart-item-exit") {
            const exitingItem = {
              ...oldItem,
              animationClass: "cart-item-exit",
            };
            next.push(exitingItem);

            // After animation ends, remove it for real
            setTimeout(() => {
              setRenderedItems((current) =>
                current.filter((c) => c.id !== oldItem.id)
              );
            }, 250); // must match CSS duration
          }
        }
      });

      return next;
    });
  }, [items]);

  return (
    <>
      <div
        className={`
          fixed top-0 right-0 h-screen md:w-[276px]
          bg-[var(--color-naviBlue)] border-l border-[#151C29]
          shadow-xl z-[9999] 
          transform transition-transform duration-500 ease-in-out
          ${open ? "translate-x-0" : "translate-x-full"}
        `}
      >
        <div className="px-4 pt-4 pb-2">
          <h2 className="text-xs md:text-sm font-sofia font-extrabold ">
            YOUR CART
          </h2>
        </div>

        {/* Close Button */}
        <button
          className="absolute top-3 right-3 text-white text-xl font-bold"
          onClick={onClose}
        >
          ✕
        </button>

        {/* Cart items list */}
        <div className="flex-1 px-4 space-y-3 mt-3 2xl:max-h-[81vh] max-h-[71vh] overflow-y-auto nice-scrollbar">
          {renderedItems.map((item) => (
            <div
              key={item.id}
              className={`
                border bg-[#121924] cursor-pointer border-[#29313D] px-3 py-3 flex gap-3
                ${item.animationClass ?? ""}
              `}
              onClick={() => handler(item)}
            >
              <div className="w-12 h-16">
                <Image
                  src={`${getFullImageUrl(item.image)}`}
                  alt={item.name}
                  width={60}
                  height={80}
                  className="w-full h-full object-contain"
                />
              </div>
              <div className="flex flex-col justify-between">
                <div>
                  <p className="text-[10px] text-[#8F8F8F] font-sofia">
                    {item.rarity}
                  </p>
                  <p className="text-sm font-extrabold font-sofia">
                    {item.name}
                  </p>
                </div>
                <span className="inline-block mt-1 rounded-full w-fit bg-[#2B5AFF26] font-onest px-3 py-1 text-xs font-extrabold text-[#DBFAFF] font-sofia">
                  {item.price}
                </span>
              </div>
            </div>
          ))}
        </div>

        {/* Totals + button */}
        <div className="px-4 font-onest border-t absolute w-full bottom-0 border-[#29313D] mt-auto">
          <div className="py-3 text-xs md:text-sm font-sofia space-y-1">
            <div className="flex justify-between">
              <span>TOTAL ITEMS</span>
              <span>{totalItems}</span>
            </div>
            <div className="flex justify-between">
              <span>TOTAL COST</span>
              <span className="font-extrabold">${totalCost.toFixed(2)}</span>
            </div>
          </div>
         <button
  className="w-full bg-[#00B020] font-onest hover:bg-[var(--color-gray)] py-3 text-xs md:text-sm font-extrabold"
  onClick={() => {
    if (!items.length) return;
    setConfirmOpen(true);
  }}
>
  ADD TO INVENTORY
</button>

        </div>
      </div>
      {/* Confirm modal */}
{confirmOpen && (
  <div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/60">
    <div className="bg-[var(--color-naviBlue)] px-6 py-6 max-w-sm 2xl:max-w-lg w-full text-center">
      <p className="text-sm md:text-xl font-sofia font-extrabold mb-6 uppercase">
        YOU ARE ABOUT TO BUY {totalItems} CARDS FOR ${totalCost.toFixed(2)}. ARE
        YOU SURE?
      </p>

      <div className="flex items-center justify-center gap-4">
        <button
          className="px-6 cursor-pointer duration-300 hover:bg-[var(--color-gray)] py-2 border border-white text-xs md:text-sm font-sofia font-extrabold"
          onClick={() => setConfirmOpen(false)}
          disabled={isBuying}
        >
          CANCEL
        </button>
        <button
          className="px-6 cursor-pointer duration-300 hover:bg-[var(--color-gray)] py-2 border border-white text-xs md:text-sm font-sofia font-extrabold"
          onClick={handleConfirmBuy}
          disabled={isBuying}
        >
          CONFIRM
        </button>
      </div>
    </div>
  </div>
)}

{/* Result modal (success / error) */}
{resultOpen && (
  <div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/60">
    <div className="bg-[var(--color-naviBlue)]  px-6 py-6 max-w-sm w-full text-center">
      <p
        className={`text-sm md:text-xl  font-sofia font-extrabold mb-6 ${
          resultType === "error" ? "text-red-400" : "text-[var(--color-parrot)]"
        }`}
      >
        {resultMsg}
      </p>

      <button
        className="px-6 py-2 border duration-300 hover:bg-[var(--color-gray)] border-white text-xs md:text-sm font-sofia font-extrabold"
        onClick={() => setResultOpen(false)}
      >
        OK
      </button>
    </div>
  </div>
)}

    </>
  );
};

export default CartSidebar;
