// app/components/trade/TradeListingCard.tsx
"use client";

import React, { useEffect, useState } from "react";
import { getTradeCards } from "@/app/lib/api/trade";
import TradeCard from "../trade/TradeCard";
import { deleteTrade } from "@/app/lib/api/list";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";

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

type TradeListingCardProps = {
  onCardClick: (card: TradeCardItem) => void;
  reloadToken?: number; // 🔹 NEW
};

const TradeListingCard: React.FC<TradeListingCardProps> = ({
  onCardClick,
  reloadToken,
}) => {
  const [listedCards, setListedCards] = useState<TradeCardItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMsg, setModalMsg] = useState("");
  const [modalType, setModalType] = useState<"success" | "error" | null>(null);
  const user = useSelector((state: any) => state.auth.user) as User | null;

  const load = async () => {
    if (!user) return;
    try {
      setLoading(true);
      setError(null);

      const data = await getTradeCards("asdf");

      const mapped: TradeCardItem[] = data.cards.map((c: any) => ({
        id: c.id,
        player: "YOU",
        timeAgo: "",
        rarity: c.rarity,
        name: c.name,
        price: `$${Number(c.price).toFixed(2)}`,
        image: c.image,
      }));

      setListedCards(mapped);
    } catch (err: any) {
      setError(err?.message || "Failed to load listed cards");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, [reloadToken]);
  const handleDelist = async (card: TradeCardItem) => {
    if (!user) return;
    try {
      const res = await deleteTrade({
        user_id: user.userId,
        id: card.id,
        token:user.token
      });

      if (res.resp === "success") {
        setListedCards((prev) => prev.filter((c) => c.id !== card.id));
        setModalType("success");
        setModalMsg(res.msg || "Card delisted successfully.");
      } else {
        setModalType("error");
        setModalMsg(res.msg || "Failed to delist card.");
      }
    } catch (err) {
      console.error("Failed to delist card", err);
      setModalType("error");
      setModalMsg("Something went wrong while delisting card.");
    } finally {
      setModalOpen(true);
      load();
    }
  };

  return (
    <div className="transition-all duration-300 w-full">
      {error && <div className="mb-4 text-red-400 text-sm">{error}</div>}

      {loading && listedCards.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 w-full gap-3 grid-cols-2 md:grid-cols-3 lg:grid-cols-5 2xl:grid-cols-6">
        {listedCards.map((card) => (
          <TradeCard
            key={card.id}
            card={card}
            onClick={() => onCardClick(card)}
            showDelist={true} // 🔹 show delist button only here
            onDelist={() => handleDelist(card)} // 🔹 call API + modal
          />
        ))}
        {!loading && listedCards.length === 0 && !error && (
          <div className="text-sm text-[var(--color-slate)] col-span-full">
            No listed cards found.
          </div>
        )}
      </div>
      {modalOpen && (
        <div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/60">
          <div className="bg-[var(--color-naviBlue)] px-6 py-4 max-w-sm w-full">
             <h3 className="text-sm md:text-xl text-center font-sofia font-extrabold mb-2">
              {modalType === "error" ? "Error" : "Success"}
            </h3>
            <p
             className={`text-sm md:text-xl text-center mb-4 ${
                modalType === "error" ? "text-red-400" : "text-green-400"
              }`}
            >
              {modalMsg}
            </p>
               <button
              onClick={() => setModalOpen(false)}
              className="w-full cursor-pointer py-2 text-sm md:text-base font-sofia font-extrabold bg-[var(--color-blue)]  hover:bg-[var(--color-hoverBlue)] duration-300"
            >
              OK
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default TradeListingCard;
