"use client";
import { CoinflipGameViewModal } from "@/app/components/coinFlip/CoinflipGameViewModal";
import { JoinGameModal } from "@/app/components/coinFlip/JoinGameModal";
import React, { useEffect, useState } from "react";
import "./style.css";
import { fetchInventoryCards, InventoryCard } from "@/app/lib/api/inventory";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import AlertModal from "@/app/components/ui/AlertModal";
import {
  createFlipGame,
  getFlipGames,
  joinFlipGame,
} from "@/app/lib/api/coinFlip";
import NotAvailable from "@/app/components/ui/NotAvailable";

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

const games: Game[] = [];

type GameItem = {
  id: number | string;
  name: string;
  price: number;
  image: string;
};

type GamePlayer = {
  name: string;
  avatar: string;
  amount: number;
  items: GameItem[];
  itemCount: number;
};

type Game = {
  name: string;
  id: number;
  leftPlayer: GamePlayer;
  rightPlayer?: GamePlayer;
  roundNumber: number;
  isJoinable: boolean;
  needsRange?: string;
  winnerSide?: "player1" | "player2" | "left" | "right" | null; // ✅ ADD THIS
};

const CoinFlipUI: React.FC = () => {
  const [isJoinModalOpen, setJoinModalOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [invCards, setInvCards] = useState<InventoryCard[]>([]);
  const [isLoadingCards, setIsLoadingCards] = useState(false);
  const [cardsError, setCardsError] = useState<string | null>(null);
  const [selectedInvCards, setSelectedInvCards] = useState<InventoryCard[]>([]);
  const [gamesState, setGamesState] = useState<Game[]>(games);
  const [selectedGame, setSelectedGame] = useState<Game | null>(null); // view modal
  const [joinTargetGameId, setJoinTargetGameId] = useState<number | null>(null); // which game to join
  const [isCreateFlow, setIsCreateFlow] = useState(false); // create vs join
  const [minJoinAmount, setMinJoinAmount] = useState<number>(0);
  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 [gamesLoading, setGamesLoading] = useState(false);
  const [gamesError, setGamesError] = useState<string | null>(null);
  const [selectedGameId, setSelectedGameId] = useState<number>();
  const [rightLocalItemsByGame, setRightLocalItemsByGame] = useState<
    Record<number, GameItem[]>
  >({});

  const [offset, setOffset] = useState<number | null>(null);
  const [hasMoreInv, setHasMoreInv] = useState(true);
  const [hasLoadedCards, setHasLoadedCards] = useState(false);
  const [isLoadingMoreInv, setIsLoadingMoreInv] = useState(false);

  const [joinGameLoading, setJoinGameLoading] = useState<boolean>(false);
  const [page, setPage] = useState(1);

  const perPage = 10;

  const totalPages = Math.max(1, Math.ceil(gamesState.length / perPage));

  const paginatedGames = gamesState.slice((page - 1) * perPage, page * perPage);

  const goToPage = (p: number) => {
    if (p < 1 || p > totalPages) return;
    setPage(p);
  };

  // Inventory Cards Laoded
  const loadCards = async (userId: any, token: any) => {
    try {
      setIsLoadingCards(true);
      setCardsError(null);

      const data = await fetchInventoryCards(userId, "yes", 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 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,
        "yes",
        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 totalItems = gamesState.reduce((sum, g) => {
    const l = g.leftPlayer?.items?.length || 0;
    const r = g.rightPlayer?.items?.length || 0;
    return sum + l + r;
  }, 0);

  const liveGames = gamesState.length;

  const loadGames = async () => {
    try {
      setGamesLoading(true);
      setGamesError(null);

      // pass token if your backend requires it:
      const apiGames = await getFlipGames(user?.token);
      console.log("apiGames", apiGames);
      apiGames.data.sort((a: any, b: any) => b.game_id - a.game_id);
      const uiGames = apiGames.data.map(mapApiGameToUiGame);
      setGamesState(uiGames);
    } catch (e: any) {
      setGamesError(e?.message || "Failed to load games");
    } finally {
      setGamesLoading(false);
    }
  };

  const toNumber = (v: any) => {
    const n = Number(v);
    return Number.isFinite(n) ? n : 0;
  };

  const buildPlayerFromSelectedCards = (cards: InventoryCard[]): GamePlayer => {
    const items: GameItem[] = cards.map((c: any, index) => ({
      id: c.inv_id ?? index + 1,
      name: c.name,
      price: Number(c.price || 0),
      image: c.image, // ✅ image url/path inventory se
    }));

    const totalValue = items.reduce((sum, i) => sum + (i.price || 0), 0);

    return {
      name: user?.name || "Unknown",
      avatar: user?.image || "/images/coinFlip/avatar.svg",
      amount: totalValue,
      items,
      itemCount: items.length,
    };
  };

  const mapApiGameToUiGame = (g: any): Game => {
    const amount = toNumber(g.price);

    const items: GameItem[] = (g.cards || []).map((img: any, idx: any) => ({
      id: `${g.game_id}-${idx}`,
      name: "Card",
      price: amount / Math.max((g.cards || []).length, 1), // optional split
      image: img,
    }));

    return {
      name: g.player1?.name || "Unknown",
      id: g.game_id,
      leftPlayer: {
        name: g.player1?.name || "Unknown",
        avatar: g.player1?.image || "/images/coinFlip/avatar.svg",
        amount,
        items,
        itemCount: items.length,
      },
      rightPlayer: undefined,
      roundNumber: Math.floor(Math.random() * 90) + 10,
      isJoinable: true,
      needsRange: "", // you can compute if needed
      winnerSide: g.w ?? null,
    };
  };

  const handleCreateGameFromCards = async (cards: InventoryCard[]) => {
    if (!user?.userId || !user?.token) {
      setModalType("error");
      setModalMsg("Please log in to play game.");
      setModalOpen(true);
      return;
    }

    try {
      // send inv_id array
      const cardIds = cards.map((c: any) => c.inv_id);

      const res = await createFlipGame({
        userId: user.userId,
        cards: cardIds,
        token: user.token,
      });
      setSelectedGameId(res?.game_id);
      setModalType("success");
      setModalMsg("Game created successfully!");
      setModalOpen(true);

      await loadGames(); // ✅ show new game dynamically
    } catch (err: any) {
      setModalType("error");
      setModalMsg(err?.message || "Failed to create game");
      setModalOpen(true);
    }
  };

  const handleJoinGameFromCards = async (
    gameId: number,
    cards: InventoryCard[],
  ) => {
    if (!user?.userId || !user?.token) {
      setModalType("error");
      setModalMsg("Please log in to play game.");
      setModalOpen(true);
      return;
    }

    const rightPlayer = buildPlayerFromSelectedCards(cards);
    setJoinModalOpen(false);
    setGamesState((prev) =>
      prev.map((g) =>
        g.id === gameId ? { ...g, rightPlayer, isJoinable: false } : g,
      ),
    );
    setJoinGameLoading(true);
    try {
      const cardIds = cards.map((c: any) => c.inv_id);

      const joined = await joinFlipGame({
        userId: user.userId,
        gameId,
        cards: cardIds,
        token: user.token,
      });
      if (joined.resp === "error") {
        setModalType("error");
        setModalMsg(joined.message || "Failed to join game");
        setModalOpen(true);
        return;
      }

      
      setGamesState((prev) =>
        prev.map((g) => {
          if (g.id !== gameId) return g;

          return {
            ...g,
            rightPlayer: g.rightPlayer
              ? {
                  ...g.rightPlayer,
                  name: joined?.player2?.name ?? g.rightPlayer.name,
                  avatar: joined?.player2?.image ?? g.rightPlayer.avatar,
                  amount: Number(
                    joined?.player2?.price ?? g.rightPlayer.amount,
                  ),
                }
              : g.rightPlayer,
            winnerSide: joined?.w ?? null, // ✅ THIS

            isJoinable: false,
          };
        }),
      );

      
      setSelectedGame((prev) =>
        prev?.id === gameId
          ? { ...prev, winnerSide: joined?.w ?? null } // ✅ THIS
          : prev,
      );

 
      setJoinGameLoading(false);
    } catch (err: any) {
      setModalType("error");
      setJoinGameLoading(false);

      setModalMsg(err?.message || "Failed to join game");
      setModalOpen(true);
    }

    const localItems: GameItem[] = cards.map((c: any, index) => ({
      id: c.inv_id ?? index + 1,
      name: c.name,
      price: Number(c.price || 0),
      image: c.image, // ✅ inventory image path
    }));

    setRightLocalItemsByGame((prev) => ({
      ...prev,
      [gameId]: localItems,
    }));
  };

  useEffect(() => {
    setPage(1);
  }, [gamesState.length]);

  useEffect(() => {
    loadGames();
  }, [user?.token]);

  return (
    <div className="min-h-screen font-sofia bg-black text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          {/* Header */}
          <header className=" z-50">
            <div className="border-b border-(--color-gray) container mx-auto py-4">
              <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
                <div className="flex items-center gap-4 md:gap-16 ">
                  <div className="text-center">
                    <div className="text-sm md:text-2xl 2xl:text-4xl font-extrabold text-(--color-blue)">
                      {totalItems}
                    </div>
                    <div className="text-sm md:text-xl font-bold tracking-tight">
                      TOTAL ITEMS
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-sm md:text-2xl 2xl:text-4xl font-extrabold text-(--color-blue)">
                      {liveGames}
                    </div>
                    <div className="text-sm md:text-xl font-bold tracking-tight">
                      LIVE GAMES
                    </div>
                  </div>
                  <button
                    className="bg-(--color-blue) hover:bg-(--color-hoverBlue) duration-300 tracking-tighter text-xs md:text-base font-onest px-3 md:px-6 py-2 rounded font-medium transition"
                    onClick={async () => {
                      if (!user) {
                        setModalType("error"); // or "login" if you have a custom type
                        setModalMsg("Please log in to play game.");
                        setModalOpen(true);
                        return;
                      }
                      setIsCreateFlow(true);
                      setJoinTargetGameId(null); // ✅ new game
                      setMinJoinAmount(0);
                      setJoinModalOpen(true);
                      await loadCards(user?.userId, user?.token);
                    }}
                  >
                    CREATE GAME
                  </button>
                </div>
              </div>
            </div>
          </header>

          <JoinGameModal
            offset={offset ?? null}
            user={user}
            cards={invCards}
            isOpen={isJoinModalOpen}
            onClose={() => setJoinModalOpen(false)}
            cardLoading={isLoadingCards}
            cardsError={cardsError}
            onConfirm={async (cards) => {
              if (isCreateFlow) {
                const cardIds = cards.map((c: any) => c.inv_id);

                const res = await createFlipGame({
                  userId: user.userId,
                  cards: cardIds,
                  token: user.token,
                });

                const leftPlayer = buildPlayerFromSelectedCards(cards);

                const newGame: Game = {
                  name: leftPlayer.name,
                  id: res?.game_id,
                  leftPlayer,
                  rightPlayer: undefined,
                  roundNumber: Math.floor(Math.random() * 90) + 10,
                  isJoinable: true,
                  needsRange: "",
                  winnerSide: null,
                };

                setSelectedGame(newGame);
                setIsModalOpen(true); // ✅ open view modal
                setJoinModalOpen(false); // ✅ close inventory modal

                
                loadGames();
              } else if (joinTargetGameId) {
                await handleJoinGameFromCards(joinTargetGameId, cards);

                const fresh =
                  gamesState.find((g) => g.id === joinTargetGameId) ?? null;
                setGamesState((prev) => {
                  const updated =
                    prev.find((g) => g.id === joinTargetGameId) ?? null;
                  setSelectedGame(updated); // ✅ always latest
                  return prev;
                });
                setIsModalOpen(true);
              }
            }}
            onAddItems={handleCreateGameFromCards}
            initialSelectedIds={selectedInvCards.map((c) => c.id)}
            minJoinAmount={minJoinAmount} // ✅ NEW
            isCreateFlow={isCreateFlow}
            onLoadMore={loadMoreInventory}
            hasMore={hasMoreInv}
            isLoadingMore={isLoadingMoreInv}
          />

          <CoinflipGameViewModal
            user={user}
            currentUser={user}
            game={selectedGame}
            isOpen={isModalOpen}
            onClose={() => {
              setModalOpen(false);
              setIsModalOpen(false);
            }}
            loadGames={loadGames}
            joinGameLoading={joinGameLoading}
          />

          {/* Games List */}
          <div className="container mx-auto py-6">
            <div className="">
              {gamesLoading ? (
                <div className="flex w-full h-65 items-center justify-center">
                  <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                </div>
              ) : (
                <>
                  {gamesError ? (
                    <div className="text-center text-sm text-red-400 py-6">
                      {gamesError}
                    </div>
                  ) : (
                    <>
                      {!gamesLoading &&
                      !gamesError &&
                      gamesState.length === 0 ? (
                        <div className="text-center text-sm text-gray-400 py-6">
                          No live games found.
                        </div>
                      ) : (
                        <>
                          {paginatedGames.map((game, id) => {
                            const rightItemsToShow = game.rightPlayer?.items
                              ?.length
                              ? game.rightPlayer.items
                              : rightLocalItemsByGame[game.id] || [];
                            return (
                              <div
                                key={game.id}
                                className={` p-4 hover:border-gray-700 transition ${
                                  id % 2 === 0
                                    ? "bg-(--color-naviBlue)"
                                    : "bg-[#121924]"
                                }`}
                              >
                                <div className="grid grid-cols-1 lg:grid-cols-[1fr_auto_1fr] gap-4 items-center">
                                  {/* Left Player */}
                                  <div className="flex items-center gap-4">
                                    <div className="w-12 h-12  rounded-full flex items-center justify-center text-2xl flex-shrink-0">
                                      <img
                                        src={game.leftPlayer.avatar}
                                        alt=""
                                        className="w-full rounded-full h-full"
                                      />
                                    </div>

                                    <div className="flex-1">
                                      <div className="text-sm flex gap-1 pr-2 items-center tracking-tighter md:text-lg 2xl:text-xl font-onest font-semibold">
                                        {!user ? (
                                          <img
                                            src="/images/header/win.svg"
                                            alt=""
                                            className="h-4 w-4"
                                          />
                                        ) : (
                                          <>
                                            {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"
                                              />
                                            )}
                                          </>
                                        )}
                                        {game.leftPlayer.amount.toFixed(2)}
                                      </div>
                                      <div className="text-xs md:text-base font-semibold text-(--color-naturalGray) -mt-1">
                                        ONLINE
                                      </div>
                                    </div>

                                    <div className="flex items-center w-full relative  gap-1">
                                      {game.leftPlayer.items
                                        .slice(0, 5)
                                        .map((img, idx) => (
                                          <div
                                            key={idx}
                                            className="w-10 h-14 relative"
                                          >
                                            <img
                                              src={`/cards${img.image}`}
                                              className="w-full h-full object-contain"
                                              alt=""
                                            />

                                            {/* Only apply gradient to LAST image */}
                                            {idx ===
                                              game.leftPlayer.items.length -
                                                1 && (
                                              <div
                                                className="pointer-events-none absolute inset-y-0 z-10 right-0 w-4 
                      bg-gradient-to-l from-[var(--color-naviBlue)] via-[var(--color-naviBlue)]/80 to-transparent"
                                              />
                                            )}
                                          </div>
                                        ))}

                                      {game.leftPlayer.itemCount && (
                                        <div className="text-xs md:text-base font-onest tracking-tighter ml-1">
                                          +{game.leftPlayer.itemCount} Items
                                        </div>
                                      )}
                                    </div>
                                  </div>

                                  {/* Center - Round Info */}
                                  <div className="flex flex-col items-center gap-2 lg:mx-8">
                                    <button
                                      onClick={() => {
                                        if (!user) {
                                          setModalType("error"); // or "login" if you have a custom type
                                          setModalMsg(
                                            "Please log in to play game.",
                                          );
                                          setModalOpen(true);
                                          return;
                                        }
                                        const fresh =
                                          gamesState.find(
                                            (g) => g.id === game.id,
                                          ) || game;
                                        setSelectedGame(fresh);
                                        setIsModalOpen(true);
                                      }}
                                      className="border border-gray-700 hover:border-gray-600 px-6 py-1 rounded font-semibold text-sm transition whitespace-nowrap"
                                    >
                                      VIEW GAME
                                    </button>
                                  </div>

                                  {/* Right Player or Empty Slot */}
                                  {game.rightPlayer ? (
                                    <div className="flex items-center gap-4 justify-end">
                                      <div className="flex items-center gap-1 justify-end w-full ">
                                        <div className="text-xs  md:text-base font-onest tracking-tighter ml-1">
                                          +{game.rightPlayer.itemCount} Items
                                        </div>
                                        {rightItemsToShow
                                          .slice(0, 5)
                                          .map((img, idx) => {
                                            return (
                                              <div
                                                key={idx}
                                                className="w-10 h-14 relative"
                                              >
                                                <img
                                                  src={img.image.replace(
                                                    "cardsimages",
                                                    "cards/images",
                                                  )}
                                                  alt="img"
                                                  className="w-full h-full object-contain"
                                                />

                                                {/* ⭐ Only apply gradient to FIRST image */}
                                                {idx === 0 && (
                                                  <div className="pointer-events-none absolute inset-y-0 z-50 left-0 w-4 bg-gradient-to-r from-[var(--color-naviBlue)] via-[var(--color-naviBlue)]/80 to-transparent" />
                                                )}
                                              </div>
                                            );
                                          })}
                                      </div>
                                      <div className="flex-1 text-right">
                                        <div className="text-sm flex gap-1 pr-2 items-center tracking-tighter md:text-lg 2xl:text-xl font-onest font-semibold">
                                          {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"
                                            />
                                          )}
                                          {game.rightPlayer.amount.toFixed(2)}
                                        </div>
                                        <div className="text-xs md:text-base font-semibold text-(--color-naturalGray) -mt-1">
                                          ONLINE
                                        </div>
                                      </div>
                                      <div className="w-12 h-12  rounded-full flex items-center justify-center text-2xl flex-shrink-0">
                                        <img
                                          src={game.rightPlayer.avatar}
                                          alt=""
                                          className="rounded-full w-full h-full"
                                        />
                                      </div>
                                    </div>
                                  ) : (
                                    <div className="flex items-center justify-end gap-4">
                                      <div className="flex items-center flex-col gap-1">
                                        <button
                                          onClick={async () => {
                                            if (!user) {
                                              setModalType("error"); // or "login" if you have a custom type
                                              setModalMsg(
                                                "Please log in to play game.",
                                              );
                                              setModalOpen(true);
                                              return;
                                            }
                                            setMinJoinAmount(
                                              game.leftPlayer.amount,
                                            );
                                            setIsCreateFlow(false);
                                            setJoinTargetGameId(game.id); // ✅ join this game
                                            setJoinModalOpen(true);
                                            await loadCards(
                                              user?.userId,
                                              user?.token,
                                            );
                                          }}
                                          className="bg-(--color-blue)  hover:bg-(--color-hoverBlue) px-6 py-2 rounded font-semibold text-sm transition whitespace-nowrap"
                                        >
                                          JOIN GAME
                                        </button>
                                      </div>
                                    </div>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </>
                      )}
                    </>
                  )}
                </>
              )}
            </div>

            {/* Pagination */}
            {!gamesLoading && !gamesError && totalPages > 1 && (
              <div className="flex font-onest justify-center items-center gap-3 m-6">
                <button
                  onClick={() => goToPage(page - 1)}
                  disabled={page === 1}
                  className="rounded-full w-8.5 h-8.5 flex justify-center items-center bg-(--color-gray) hover:bg-(--color-gray) disabled:opacity-40"
                >
                  <img src="/images/profile/left.svg" alt="" />
                </button>

                <div className="flex gap-2 text-sm">
                  {[...Array(totalPages)].map((_, i) => {
                    const pg = i + 1;

                    if (
                      pg === 1 ||
                      pg === totalPages ||
                      Math.abs(pg - page) <= 1
                    ) {
                      return (
                        <button
                          key={pg}
                          onClick={() => goToPage(pg)}
                          className={`px-3 py-1 rounded ${
                            pg === page
                              ? "scale-115 text-white"
                              : "text-(--color-naturalGray)"
                          }`}
                        >
                          {pg}
                        </button>
                      );
                    }

                    if (pg === page - 2 || pg === page + 2) {
                      return (
                        <span
                          key={`ellipsis-${pg}`}
                          className="px-2 text-gray-400"
                        >
                          ...
                        </span>
                      );
                    }

                    return null;
                  })}
                </div>

                <button
                  onClick={() => goToPage(page + 1)}
                  disabled={page === totalPages}
                  className="flex justify-center items-center w-8.5 h-8.5 rounded-full bg-(--color-gray) hover:bg-(--color-gray) disabled:opacity-40"
                >
                  <img src="/images/profile/right.svg" alt="" />
                </button>
              </div>
            )}
          </div>

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

export default CoinFlipUI;
