"use client";
import React, { ReactNode, useEffect, useState } from "react";
import Image from "next/image";
import { InventoryCard } from "@/app/lib/api/inventory";
import { buyOneTrade } from "@/app/lib/api/trade";
import AlertModal from "../ui/AlertModal";
import { useSelector } from "react-redux";
import { AuthState } from "@/app/wallet/page";

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

type Props = {
  selectedCard: TradeCardItem | null;
  setSelectedCard: React.Dispatch<React.SetStateAction<TradeCardItem | null>>;
  setshowTradingRaging: React.Dispatch<React.SetStateAction<boolean>>;
  setOpenInventory: React.Dispatch<React.SetStateAction<boolean>>;
  getFullImageUrl: (img: string) => string;
  selectedInvCards: InventoryCard[];
  onRemoveInvCard: (cardId: number) => void;
  userId: string; // ✅ add
  token: string;
  setSelectedInvCards: any;
  loadTradeCards: (force?: boolean) => Promise<void>;
  loadCards: () => void;
};

const TradingRagingView: React.FC<Props> = ({
  selectedCard,
  setSelectedCard,
  setshowTradingRaging,
  setOpenInventory,
  getFullImageUrl,
  selectedInvCards,
  onRemoveInvCard,
  userId,
  token,
  setSelectedInvCards,
  loadTradeCards,
  loadCards,
}) => {
  const [tradeSuccess, setTradeSuccess] = useState(false);
  const selectedPrice = selectedCard
    ? Number(selectedCard.price.replace("$", ""))
    : 0;

  // const valueNeeded = selectedPrice * 1.05; // 5% more than selected card price
  const valueNeeded = selectedPrice;
  const currentValue = selectedInvCards.reduce(
    (sum, card) => sum + (Number(card.price) || 0),
    0,
  );

  const [isTrading, setIsTrading] = useState(false);

  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState<ReactNode>(null);
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  const handleTrade = async () => {
    if (!selectedCard) return;

    if (currentValue < valueNeeded) {
      setModalType("error");
      setModalMsg(
        <span className="text-base">
          Not enough value. You need{" "}
          {user?.activeMode === "coins" ? (
            <img
              src="/images/header/win.svg"
              alt="coins"
              className="h-4 w-4  inline-block"
            />
          ) : (
            <img
              src="/images/header/star.svg"
              alt="gems"
              className="h-4 w-4 inline-block"
            />
          )}
          {valueNeeded.toFixed(2)} but you have{" "}
          {user?.activeMode === "coins" ? (
            <img
              src="/images/header/win.svg"
              alt="coins"
              className="h-4 w-4 inline-block"
            />
          ) : (
            <img
              src="/images/header/star.svg"
              alt="gems"
              className="h-4 w-4 inline-block"
            />
          )}
          {currentValue.toFixed(2)}
        </span>,
      );

      setModalOpen(true);
      return;
    }
    const user_id = userId;
    const trad_card = selectedCard.id;
    const cards = selectedInvCards.map((c: any) => c.inv_id ?? c.id);

    try {
      setIsTrading(true);

      const res: any = await buyOneTrade(user_id, trad_card, cards, token);

      const hasError =
        res?.error === true ||
        res?.resp?.error === true ||
        res?.resp === "error" ||
        res?.status === "error";

      if (hasError) {
        const msg =
          res?.message ||
          res?.resp?.message ||
          res?.errorMessage ||
          "Something went wrong";

        setModalType("error");
        setModalMsg(msg);
        setModalOpen(true);
        return;
      }
      console.log("res of buyonetrade", res);
      if (res.resp === "success") {
        await loadTradeCards(true);
        // ✅ SUCCESS
        setModalType("success");
        setModalMsg(res?.message || "Card purchased successfully.");
        setModalOpen(true);

        setTradeSuccess(true);
        setSelectedInvCards([]);
        setTimeout(() => {
          setshowTradingRaging(false);
        }, 3000);
      }
    } catch (e: any) {
      const msg = e?.response?.data?.message || e?.message || "Trade failed";
      setModalType("error");
      setModalMsg(msg);
      setModalOpen(true);
      setSelectedInvCards([]);
    } finally {
      setIsTrading(false);
      setSelectedInvCards([]);
    }
  };

  return (
    <>
      <div className="flex mt-1.5 items-center justify-between">
        <div className="flex items-center gap-4">
          <button
            onClick={async () => {
              setshowTradingRaging(false);
              setSelectedCard(null);
              // await loadTradeCards(true);
            }}
            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 uppercase md:text-2xl font-extrabold italic">
            trading {selectedCard?.name ?? ""}
          </h1>
        </div>
      </div>

      <div className="mt-4 border border-[#29313D] bg-[#121924]">
        {/* top info bar */}
        {tradeSuccess && (
          <div className="border-b border-[#29313D] px-4 font-onest py-3 text-center text-sm md:text-base">
            {tradeSuccess ? "Trade Successful!" : ""}
            {/* Your card(s) should be <b>5% more</b> in value to the trade card */}
          </div>
        )}

        {/* main trade layout */}
        <div className=" p-6">
          <div
            className={`grid grid-cols-1 gap-3 md:gap-6 items-center ${
              tradeSuccess
                ? "grid-cols-1"
                : "md:grid-cols-[280px_80px_minmax(0,1fr)]"
            }`}
          >
            {/* LEFT: Selected trade card */}
            <div>
              {selectedCard ? (
                <>
                  <div
                    className={`flex flex-col items-center bg-[#161E2A] py-4 ${
                      tradeSuccess ? "w-fit px-6 mx-auto" : ""
                    }`}
                  >
                    <Image
                      src={getFullImageUrl(selectedCard.image)}
                      alt={selectedCard.name}
                      width={220}
                      height={300}
                      className="w-20 img-border-radius"
                    />

                    <div className="mt-2 relative z-20 text-center">
                      <p className="text-[10px] md:text-base font-sofia text-[#DBFAFF] ">
                        {selectedCard.rarity}
                      </p>
                      <p className="text-sm md:text-xl font-extrabold font-sofia">
                        {selectedCard.name.split(" ").slice(0, 2).join(" ")}
                      </p>
                    </div>

                    <button className="mt-1 flex items-center gap-1 rounded-md bg-[#2B5AFF26] px-6 py-1 text-sm md:text-xl font-extrabold text-[#DBFAFF] font-sofia">
                      {user?.activeMode === "coins" ? (
                        <img
                          src="/images/header/win.svg"
                          alt=""
                          className="h-4 w-4"
                        />
                      ) : (
                        <img
                          src="/images/header/star.svg"
                          alt=""
                          className="h-4 w-4"
                        />
                      )}{" "}
                      {selectedCard.price.replace("$", "")}
                    </button>
                  </div>
                  {!tradeSuccess && (
                    <div className="flex justify-center">
                      <button
                        className={`
                        ${
                          selectedInvCards?.length > 0
                            ? "bg-[var(--color-blue)] hover:bg-[var(--color-hoverBlue)] duration-300 "
                            : "bg-[#8F8F8F] cursor-not-allowed pointer-events-none"
                        }
                        mt-4 px-10 w-full text-white font-extrabold py-3 hover:opacity-90`}
                        onClick={handleTrade}
                      >
                        TRADE
                      </button>
                    </div>
                  )}
                </>
              ) : (
                <div className="text-center opacity-70">No card selected</div>
              )}
            </div>
            {tradeSuccess && (
              <div
                onClick={() => {
                  setTradeSuccess(!tradeSuccess);
                }}
                className="flex cursor-pointer items-center w-full justify-center gap-3"
              >
                <div className="rounded-full p-2 bg-[#2B5AFF26]">
                  <img src="/images/trade/tick.svg" alt="" />
                </div>
                <p className="font-onest font-semibold text-sm md:text-2xl">
                  Added to Inventory
                </p>
              </div>
            )}

            {/* middle swap icon */}
            <div
              className={`flex justify-center ${tradeSuccess ? "hidden" : ""}`}
            >
              <div className="w-14 h-14 rounded-full border p-3 border-[#54657E] flex items-center justify-center bg-[#29313D]">
                {/* simple swap icon */}
                <img src="/images/trade/trading.svg" alt="" />
              </div>
            </div>

            {/* RIGHT: add inventory cards area */}
            <div className={`${tradeSuccess ? "hidden" : ""} min-w-0`}>
              <div className="bg-[bg-[#161E2A]] border border-[#29313D] min-h-53.25 flex items-center justify-center">
                {selectedInvCards?.length === 0 ? (
                  <button
                    onClick={() => {
                      loadCards();
                      setOpenInventory(true);
                    }}
                    className="text-6xl opacity-80 hover:opacity-100 cursor-pointer transition"
                    aria-label="Add cards"
                  >
                    <img src="/images/trade/plus.svg" className="w-14" alt="" />
                  </button>
                ) : (
                  <div className="w-full max-w-full p-4 overflow-x-auto overflow-y-hidden">
                    <div className="flex gap-4 w-max">
                      {selectedInvCards?.map((c, index) => (
                        <div
                          onClick={() => onRemoveInvCard(c.inv_id)}
                          key={index}
                          className="cursor-pointer text-center"
                        >
                          <img
                            src={c.image.replace("cardsimages", "cards/images")}
                            className="h-24 w-auto object-contain img-border-radius mx-auto"
                            alt={c.name}
                          />
                          <div className="mt-2 flex items-center gap-1 text-sm font-extrabold text-white">
                            {user?.activeMode === "coins" ? (
                              <img
                                src="/images/header/win.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            ) : (
                              <img
                                src="/images/header/star.svg"
                                alt=""
                                className="h-4 w-4"
                              />
                            )}{" "}
                            {c.price.toFixed(2)}
                          </div>
                        </div>
                      ))}
                      {/* add more */}
                      <button
                        onClick={() => setOpenInventory(true)}
                        className="shrink-0 w-24 h-24 border border-[#29313D] flex items-center justify-center hover:opacity-90"
                        aria-label="Add more cards"
                      >
                        <img
                          src="/images/trade/plus.svg"
                          className="w-8"
                          alt=""
                        />
                      </button>
                    </div>
                  </div>
                )}
              </div>

              {/* bottom values */}
              <div className="mt-6 items-center grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="border font-bold text-base md:text-xl border-[#29313D] items-center bg-[var(--color-black)] p-4 flex justify-between">
                  <span className="uppercase text-white">Value needed:</span>
                  <span className="font-extrabold flex items-center gap-1 text-[#DBFAFF]">
                    {user?.activeMode === "coins" ? (
                      <img
                        src="/images/header/win.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    ) : (
                      <img
                        src="/images/header/star.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    )}{" "}
                    {valueNeeded.toFixed(2)}
                  </span>
                </div>
                <div className="border font-bold text-base md:text-xl border-[#29313D] items-center bg-[var(--color-black)] p-4 flex justify-between">
                  <span className="uppercase text-white">Current:</span>
                  <span className="flex items-center gap-1 font-extrabold text-[#DBFAFF]">
                    {user?.activeMode === "coins" ? (
                      <img
                        src="/images/header/win.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    ) : (
                      <img
                        src="/images/header/star.svg"
                        alt=""
                        className="h-4 w-4"
                      />
                    )}{" "}
                    {currentValue.toFixed(2)}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <AlertModal
          open={modalOpen}
          type={modalType}
          message={modalMsg}
          onClose={() => setModalOpen(false)}
        />
      </div>
    </>
  );
};

export default TradingRagingView;
