"use client";
import { useEffect, useMemo, useState } from "react";
import BetModal from "../components/sports/BetModal";
import MatchTabs, { GameTab } from "../components/sports/MatchTabs";
import {
  fetchBets,
  fetchEvents,
  fetchLeagues,
  fetchPlayers,
  fetchSports,
  fetchStats,
  fetchTeams,
  placeBet,
} from "../lib/api/sport";
import AlertModal from "../components/ui/AlertModal";
import { fetchInventoryCards, InventoryCard } from "../lib/api/inventory";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import MyBets from "../components/sports/MyBets";
import { sendRequest } from "@/constants/index";

type ChildTab = "all" | string; // sportID: "SOCCER" | "BASEBALL" etc

type ParentTab = "all" | "upcoming" | "live";

type Card = {
  id: number;
  name: string;
  rarity: string;
  price: number;
  image: string;
};

type SportRow = {
  id: number;
  sportID: string;
  name: string;
  shortName: string;
};

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

const ODDS = 1.53; // 1.53 like your screenshot

const betCards: Card[] = [
  {
    id: 1,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg", // <- change to your card image path
  },

  // duplicate for demo – you can replace with real data
  {
    id: 2,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },

  {
    id: 3,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 4,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 5,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 6,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 7,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 8,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 9,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 10,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 11,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 12,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 13,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
  {
    id: 14,
    name: "RAGING BOLT EX",
    rarity: "HOLOFOIL",
    price: 100,
    image: "/images/sports/img.svg",
  },
];

const sportIconMap: Record<string, string> = {
  BASKETBALL: "/images/sports/basketball.svg",
  FOOTBALL: "/images/sports/football.svg",
  BASEBALL: "/images/sports/baseball.svg",
  SOCCER: "/images/sports/soccer.svg",
  HOCKEY: "/images/sports/hockey.svg",
  TENNIS: "/images/sports/tennis.svg",
  HANDBALL: "/images/sports/handball.svg",
  GOLF: "/images/sports/golf.svg",
  MMA: "/images/sports/mma.svg",
  HORSE_RACING: "/images/sports/horse-racing.svg",
  NON_SPORTS: "/images/sports/non-sports.svg",
};

const Inner = () => {
  const [parentTab, setParentTab] = useState<ParentTab>("all");
  const [childTab, setChildTab] = useState<ChildTab>("soccer");
  const [showBetModal, setShowBetModal] = useState(false);
  const [selectedCardIds, setSelectedCardIds] = useState<number[]>([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"error" | "success">("error");
  const [modalMsg, setModalMsg] = useState("");
  const [gameTabs, setGameTabs] = useState<GameTab[]>([]);
  const [loadingLeagues, setLoadingLeagues] = useState(false);
  const [isLoadingCards, setIsLoadingCards] = useState(false);
  const [cardsError, setCardsError] = useState<string | null>(null);
  const [invCards, setInvCards] = useState<InventoryCard[]>([]);
  const [leagueEvents, setLeagueEvents] = useState<any>([]);
  const [single_event, set_single_event] = useState<any>({});
  const [mybets, setMyBets] = useState<any[]>([]);
  const [isBets, setIsBets] = useState(false);
  const [leaguesBettingData, setLeaguesBettingData] = useState<any[]>([]);
  const [offset, setOffset] = useState<number | null>(null);
  const [hasMoreInv, setHasMoreInv] = useState(true);
  const [hasLoadedCards, setHasLoadedCards] = useState(false);
  const [isLoadingMoreInv, setIsLoadingMoreInv] = useState(false);
  const [more, setMore] = useState<"yes" | "no">("no");
  const [league, setLeague] = useState(null); // from /leagues API
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  const pageSize = 7;

  const [page, setPage] = useState(1);

  const totalPages = Math.ceil((leagueEvents?.length || 0) / pageSize) || 1;

  const paginatedLeagueEvents = (leagueEvents || []).slice(
    (page - 1) * pageSize,
    page * pageSize,
  );

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  // 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);
      setMore(data.more as "yes" | "no");
      setHasMoreInv(data.more === "yes");
      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
        return;
      }

      setInvCards((prev) => [...prev, ...data.cards]); // ✅ append
      setOffset(data.offset ?? null); // ✅ next offset
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoadingMoreInv(false);
    }
  };

  const toggleCard = (id: number) => {
    setSelectedCardIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
    );
  };

  const totalValue = selectedCardIds.reduce((sum, id) => {
    const card = betCards.find((c) => c.id === id);
    return sum + (card?.price ?? 0);
  }, 0);

  const getEvents = async (sport: any, sub: any) => {
    setLoadingLeagues(true);
    let sb = sub ?? "";
    try {
      sendRequest(
        {
          action:
            "get-events?sport=" + sport + "&tag=" + sb + "&wh=" + parentTab,
        },
        await function (resp: any) {
          if (resp?.resp != "error") {
            setLeagueEvents(resp.events);
            setLoadingLeagues(false);
          } else {
            // setLoadingLeagues(false);
          }
        },
      );
    } catch (e: any) {
      // setModalType("error");
      // setModalMsg(e.message || "Failed to load events");
      // setModalOpen(true);
      // setLoadingLeagues(false);
    } finally {
      // setLoadingLeagues(false);
    }
  };

  const getBets = async () => {
    try {
      const res = await fetchBets(user?.userId, user?.token);
      setMyBets(res.data || []);
    } catch (e: any) {
      // setModalType("error");
      // setModalMsg(e.message || "Failed to load Bets");
      // setModalOpen(true);
      // console.log("error", e.message);
    }
  };

  useEffect(() => {
    getBets();
  }, []);

  useEffect(() => {
    setPage(1);
  }, [leagueEvents]);

  useEffect(() => {
    const tabs: GameTab[] = [
      {
        id: "soccer",
        name: "Soccer",
        icon: sportIconMap["SOCCER"],
        leagues: [
          {
            id: "epl",
            name: "English Premier League",
            icon: "/images/sports/leagues/soccer-english-premier-league.webp",
          },
          {
            id: "mls",
            name: "Major League Soccer",
            icon: "/images/sports/leagues/soccer-major-league-soccer.webp",
          },
          {
            id: "fifa",
            name: "FIFA World Cup",
            icon: "/images/sports/leagues/soccer-fifa-world-cup.webp",
          },
          {
            id: "ucl",
            name: "UEFA Champions League",
            icon: "/images/sports/leagues/soccer-uefa.webp",
          },
        ],
      },

      {
        id: "basketball",
        name: "BasketBall",
        icon: sportIconMap["BASKETBALL"],
        leagues: [
          {
            id: "nba",
            name: "NBA",
            icon: "/images/sports/leagues/basketball-nba.png",
          },
          {
            id: "ncaab",
            name: "NCAA Basketball",
            icon: "/images/sports/leagues/basketball-ncaa.webp",
          },
        ],
      },

      {
        id: "baseball",
        name: "Baseball",
        icon: sportIconMap["BASEBALL"],
        leagues: [
          {
            id: "mlb",
            name: "MLB",
            icon: "/images/sports/leagues/baseball-mlb.png",
          },
        ],
      },

      {
        id: "ice-hockey",
        name: "Ice Hockey",
        icon: sportIconMap["HOCKEY"],
        leagues: [
          // ✅ add NHL icon if you have it in folder
          {
            id: "nhl",
            name: "NHL",
            icon: "/images/sports/leagues/hockey-nhl.webp",
          },
        ],
      },

      {
        id: "tennis",
        name: "Tennis",
        icon: sportIconMap["TENNIS"],
        leagues: [
          // ✅ add if you have icons
          {
            id: "atp",
            name: "ATP Tour",
            icon: "/images/sports/leagues/tennis-atp.webp",
          },
          {
            id: "wta",
            name: "WTA Tour",
            icon: "/images/sports/leagues/tennis-wta.webp",
          },
        ],
      },

      {
        id: "handball",
        name: "Handball",
        icon: sportIconMap["HANDBALL"],
        leagues: [],
      },

      {
        id: "esports",
        name: "Esports",
        icon: sportIconMap["NON_SPORTS"],
        leagues: [
          {
            id: "cs2",
            name: "CS2",
            icon: "/images/sports/leagues/esports-cs2.webp",
          },
          {
            id: "lol",
            name: "League of Legends",
            icon: "/images/sports/leagues/esport-league-of-legends.webp",
          },
          {
            id: "dota2",
            name: "Dota 2",
            icon: "/images/sports/leagues/esport-dota-2.webp",
          },
          {
            id: "val",
            name: "Valorant",
            icon: "/images/sports/leagues/esport-valorant.png",
          },
          {
            id: "r6",
            name: "Rainbow Six Siege",
            icon: "/images/sports/leagues/esport-rainbow.webp",
          },
          {
            id: "cod",
            name: "Call of Duty",
            icon: "/images/sports/leagues/esport-Cod.webp",
          },
        ],
      },
    ];

    setGameTabs(tabs);
  }, []);

  useEffect(() => {
    // if (childTab === "all") return;
    console.log(childTab, league);
    getEvents(childTab, league);
  }, [childTab, league]);

  useEffect(() => {
    if (!user) {
      setModalType("error"); // or "login" if you have a custom type
      setModalMsg("Please log in to see marketeplace.");
      setModalOpen(true);
      return;
    }
    if (!hasLoadedCards) {
      (async () => {
        await loadCards(user?.userId, user?.token);
      })();
    }
  }, [hasLoadedCards]);

  const potentialReward = totalValue * ODDS;

  function hasPassedHours(startTime: any, hours = 3) {
    return Date.now() - new Date(startTime).getTime() >= hours * 60 * 60 * 1000;
  }

  return (
    <div className="min-h-screen bg-black text-white">
      <div className="container mx-auto py-2 ">
        {isBets ? (
          <MyBets onBack={() => setIsBets(false)} mybets={mybets} />
        ) : (
          <>
            <div className="flex flex-col lg:flex-row gap-3 items-center justify-between">
              <button
                onClick={() => {
                  setIsBets(true);
                }}
                className="border cursor-pointer font-onest gap-2 font-bold text-sm md:text-base flex items-center border-[#4D4CFE] px-5 py-2 bg-[#2B5AFF26] md:px-12"
              >
                <span>MY BETS</span>
                <span className="bg-[#F14B3F] rounded-full w-5.5 h-5.5 flex items-center justify-center font-bold text-xs">
                  {mybets.length}
                </span>
              </button>
            </div>
            <MatchTabs
              parentTab={parentTab}
              setParentTab={setParentTab}
              childTab={childTab}
              setChildTab={setChildTab}
              setLeague={setLeague}
              gameTabs={gameTabs}
            />

            {loadingLeagues ? (
              <div className="flex w-full h-20 items-center justify-center">
                <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
              </div>
            ) : (
              <>
                {paginatedLeagueEvents.length === 0 && (
                  <div className="p-6 text-center text-sm font-onest text-white/50">
                    No events found.
                  </div>
                )}
                {paginatedLeagueEvents?.map((event: any, index: any) => {
                  let team1 = event.teams[0];
                  let team2 = event.teams[1];
                  let event_icon = event.icon;
                  let series = event.series[0];
                  let series_name = series.title;
                  let startDate = event.startTime;

                  let score = "";
                  let is_live = false;
                  if (event?.live) {
                    let _is_lv = event?.live == true ? true : false;
                    is_live = _is_lv;
                    score = event.score;
                    if (score.includes("|")) {
                      let sptl = score.split("|");
                      let period = event.period.split("/");
                      score =
                        sptl[1] +
                        " | Game " +
                        period[0] +
                        " | Best of " +
                        period[1];
                    }
                  }

                  const date = event.cs_date;
                  const time = event.cs_time;
                  const markets = event.markets;

                  let prices = JSON.parse(markets[0].outcomePrices);

                  let team1_price = (prices[0] * 100).toFixed(0);
                  let team2_price = (prices[1] * 100).toFixed(0);

                  // const meta = leagueMetaMap[league.leagueID];
                  // const leagueTitle =
                  //   meta?.longName || meta?.name || league.leagueID;

                  return (
                    <div className="" key={index}>
                      <div className="mb-2">
                        <div className="mt-4">
                          <div className="flex flex-col lg:flex-row flex-wrap gap-3 border py-2 px-4 text-white font-bold text-base md:text-xl 2xl:text-2xl   border-[#29313D] bg-[#121924] items-center justify-between">
                            <div className=""></div>
                            <div className="flex  items-center gap-3 justify-center ">
                              <img
                                src={event_icon}
                                alt={series.seriesSlug}
                                style={{
                                  width: "35px",
                                  height: "35px",
                                  borderRadius: "100%",
                                }}
                              />
                              {/* <h1>{team1.name}</h1> vs 
                                    <h1>{team2.name}</h1> */}
                              <h1>{series_name}</h1>
                            </div>
                            <div className="uppercase">
                              {/* {event.status.displayLong} */}
                            </div>
                          </div>
                        </div>
                        {/* For Live */}
                        <div className=" p-1 px-3 border border-t-0 justify-between border-[#29313D] bg-[#161E2A] items-center gap-3 text-white font-bold text-base md:text-2xl 2xl:text-4xl ">
                          {is_live ? (
                            <div className="flex w-full gap-3  text-sm md:text-base font-bold items-center justify-center">
                              <div className="flex text-[#FF348D] !items-center gap-1">
                                <span className="mb-2">.</span>
                                <span className=""> LIVE</span>
                              </div>
                              <span className="text-xs md:text-sm text-[#54657E]">
                                {score}
                              </span>{" "}
                              {/* <span className="text-xs md:text-sm font-onest text-[#54657E]">
                                      78:45
                                    </span> */}
                            </div>
                          ) : null}
                        </div>
                        <div className="flex flex-col lg:flex-row flex-wrap gap-3 p-1 px-3 border border-t-0 justify-between border-[#29313D] bg-[#161E2A] items-center text-white font-bold text-base md:text-2xl 2xl:text-4xl  ">
                          <div className="flex flex-1 flex-col lg:flex-row items-center justify-between gap-2">
                            <div className="flex font-sofia text-sm md:text-lg 2xl:text-2xl items-center gap-5">
                              <h1>{date}</h1>
                              <h1>{time}</h1>
                            </div>
                            <div className="flex text-xs md:text-base 2xl:text-lg hover:border-[#4D4CFE] duration-300 cursor-pointer hover:bg-[#2B5AFF26]  border-2 pl-5 justify-between gap-4 md:w-[400px] border-[#29313D] ">
                              <div className="flex items-center gap-2">
                                {/* <img
                                  src={team1.logo}
                                  alt={team1.name}
                                  style={{ height: "40px" }}
                                /> */}
                                <h1>
                                  {team1.name}
                                  &nbsp; &nbsp;{" "}
                                  <small style={{ color: "#ccc" }}>
                                    {team1.record}
                                  </small>
                                </h1>
                              </div>
                              <div className="bg-[#13151A] p-2">
                                {team1_price} ¢
                              </div>
                            </div>
                          </div>

                          <div className="flex flex-1 items-center justify-between gap-2">
                            <div className="flex text-xs md:text-base 2xl:text-lg hover:border-[#4D4CFE] duration-300 cursor-pointer hover:bg-[#2B5AFF26]  border-2 pr-5 justify-between gap-4 md:w-[400px] border-[#29313D] ">
                              <div className="bg-[#13151A] p-2">
                                {team2_price} ¢
                              </div>

                              <div className="flex items-center gap-2">
                                <h1>
                                  {team2.name}
                                  &nbsp; &nbsp;{" "}
                                  <small style={{ color: "#ccc" }}>
                                    {team2.record}
                                  </small>
                                </h1>
                                {/* <img
                                  src={team2.logo}
                                  alt={team2.name}
                                  style={{ height: "40px" }}
                                /> */}
                              </div>
                            </div>
                          </div>

                          <div className="text-white">
                            {is_live ? (
                              <div className="flex items-center gap-2">
                                <a
                                  href="#"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    setShowBetModal(true);
                                    set_single_event(event);
                                  }}
                                  className="italic underline text-xs md:text-sm"
                                >
                                  set bets &gt;
                                </a>
                              </div>
                            ) : (
                              <div className="flex items-center gap-2">
                                <a
                                  href="#"
                                  onClick={async (e) => {
                                    e.preventDefault();
                                    setShowBetModal(true);
                                    set_single_event(event);
                                    // setIsBets(true);
                                    await loadCards(user?.userId, user?.token);
                                  }}
                                  className="italic underline text-xs md:text-sm"
                                >
                                  SET MY BET &gt;
                                </a>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
                {totalPages > 1 && (
                  <div className="flex justify-center items-center gap-3 m-6">
                    <button
                      onClick={() => goToPage(page - 1)}
                      disabled={page === 1}
                      className="rounded-full w-[34px] h-[34px] flex justify-center items-center bg-[var(--color-gray)] hover:bg-[var(--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-[var(--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-[34px] h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
                    >
                      <img src="/images/profile/right.svg" alt="" />
                    </button>
                  </div>
                )}
              </>
            )}

            <div className="">
              {showBetModal && (
                <BetModal
                  user={user}
                  leaguesBettingData={leaguesBettingData}
                  event={single_event}
                  cards={invCards}
                  cardLoading={isLoadingCards}
                  cardsError={cardsError}
                  isOpen={showBetModal}
                  onClose={() => setShowBetModal(false)}
                  odds={ODDS}
                  betCards={betCards}
                  selectedCardIds={selectedCardIds}
                  toggleCard={toggleCard}
                  totalValue={totalValue}
                  potentialReward={potentialReward}
                  onPlaceBet={() => console.log("place bet")}
                  onLoadMore={loadMoreInventory}
                  hasMore={hasMoreInv}
                  isLoadingMore={isLoadingMoreInv}
                />
              )}
            </div>
          </>
        )}

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

export default Inner;
