import { InventoryCard } from "@/app/lib/api/inventory";
import { placeBet } from "@/app/lib/api/sport";
import { User } from "@/constants/types";
import React, { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import AlertModal from "../ui/AlertModal";
type Team = {
  name: string;
  icon: string;
};

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

interface BetModalProps {
  isOpen: boolean;
  onClose: () => void;
  odds: number;

  matchTitle?: string;
  matchMeta?: string;
  dateLabel?: string;
  timeLabel?: string;

  leftTeam?: Team;
  rightTeam?: Team;

  betCards: BetCard[];
  selectedCardIds: Array<string | number>;

  toggleCard: (id: any) => void;

  totalValue: number;
  potentialReward: number;

  onPlaceBet: () => void;
  cards: InventoryCard[] | null;
  cardLoading: boolean;
  cardsError: string | null;

  event?: any;
  leaguesBettingData?: any;
  user: User;
  onLoadMore: () => Promise<void>;

  hasMore: boolean;
  isLoadingMore: boolean;
}

interface Item extends InventoryCard {
  selected?: boolean;
}

export default function BetModal({
  isOpen,
  onClose,
  odds,

  leftTeam = { name: "YOUNG NINJAS", icon: "/images/sports/star.svg" },
  rightTeam = { name: "MANA ESPORTS", icon: "/images/sports/badge.svg" },
  betCards = [],
  selectedCardIds = [],
  toggleCard,
  totalValue = 0,
  potentialReward = 0,
  onPlaceBet,
  cards,
  cardLoading,
  cardsError,
  event,
  leaguesBettingData,
  user,
  onLoadMore,
  hasMore,
  isLoadingMore,
}: BetModalProps) {
  if (!isOpen) return null;

  // const selectedCards = betCards.filter((c) => selectedCardIds.includes(c.id));
  const STEP = 10;
  const [visibleCount, setVisibleCount] = useState(STEP);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const [mounted, setMounted] = useState(false);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [betLoading, setBetLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"error" | "success">("error");
  const [modalMsg, setModalMsg] = useState("");
  const [bet_odd, set_bet_odd] = useState(0);
  const [selectedTeam, setSelectedTeam] = useState<"home" | "away" | null>(
    null,
  );
  const [apiLoading, setApiLoading] = useState(false);

  const [teamId, setTeamId] = useState<string>("");
  // click toggle
  const toggleSelect = (inv_id: number) => {
    setSelectedIds((prev) =>
      prev.includes(inv_id)
        ? prev.filter((x) => x !== inv_id)
        : [...prev, inv_id],
    );
  };

  const selectedCards = (cards || []).filter((c: any) =>
    selectedIds.includes(c.inv_id),
  );

  const totalValueLocal = selectedCards.reduce(
    (sum: number, c: any) => sum + (Number(c.price) || 0),
    0,
  );

  // only visible cards (10, 20, 30...)
  const visibleCards = (cards || []).slice(0, visibleCount);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const el = e.currentTarget;
    const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 120;
    if (!nearBottom) return;

    // ✅ First: show more from already-loaded cards
    if (!isFetchingMore && visibleCount < (cards?.length ?? 0)) {
      setIsFetchingMore(true);
      setTimeout(() => {
        setVisibleCount((c) => Math.min(c + STEP, cards?.length ?? 0));
        setIsFetchingMore(false);
      }, 150);
      return;
    }

    // ✅ Second: if everything visible AND backend still has more, call API
    if (visibleCount >= (cards?.length ?? 0) && hasMore && !apiLoading) {
      setApiLoading(true);
      Promise.resolve(onLoadMore()).finally(() => setApiLoading(false));
    }
  };

  const handlePlaceBet = async (cards: any) => {
    try {
      setBetLoading(true);

      const res = await placeBet(
        user?.userId,
        user.token,
        event.id,
        teamId,
        cards,
        bet_odd
      );
      if (res.resp === "success") {
        onClose();
        setModalType("success");
        setModalMsg("Bet placed successfully!");
        setModalOpen(true);
      }
      // optional: refresh leagues/bets
      // await fetchLeagues();
    } catch (e: any) {
      setModalType("error");
      setModalMsg(e.message || "Failed to place bet. Please try again.");
      setModalOpen(true);
    } finally {
      setBetLoading(false);
    }
  };

  // modal open pe reset
  useEffect(() => {
    if (!isOpen) return;
    setVisibleCount(STEP);
    setSelectedIds([]);
    requestAnimationFrame(() => {
      if (scrollRef.current) scrollRef.current.scrollTop = 0;
    });
  }, [isOpen]);
  useEffect(()=>{
    let t1 = event.teams[0];
    let t2 = event.teams[1];
    let prices = JSON.parse(markets[0].outcomePrices);
    let team1_price = prices[0];
    let team2_price = prices[1];
    if (t1.id == teamId){
      set_bet_odd(team1_price);
    }else if (t2.id == teamId){
      set_bet_odd(team2_price);
    }
  }, [teamId]);
  useEffect(() => setMounted(true), []);
  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.startDate;

  const dateObj = new Date(startDate);
  const date = dateObj.toISOString().split("T")[0];
  const time = dateObj
                  .toISOString()
                    .split("T")[1]
                    .split(".")[0];
  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 win_price = () => {
    let t  =  isNaN(totalValueLocal) ? 0 : parseFloat(totalValueLocal);
    let b = isNaN(bet_odd) ? 0 : parseFloat(bet_odd);
    if (t > 0){
      return b > 0 ? (t / b).toFixed(2) : t.toFixed(2);
    }else{
      return 0.
    }
  }


  // const date = d
  //   .toLocaleDateString("en-US", {
  //     month: "short",
  //     day: "numeric",
  //     year: "numeric",
  //   })
  //   .toUpperCase();
  // const time = d.toLocaleTimeString("en-US", {
  //   hour: "2-digit",
  //   minute: "2-digit",
  //   hour12: false,
  // });

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/90">
      <div className="bg-[#0F1722] max-w-5xl border border-(--color-gray) w-full mx-4 overflow-hidden">
        {/* Top header bar */}
        <div className="flex items-center justify-between px-4 py-3 bg-[#111827] border-b border-[#29313D]">
          <div className="flex !font-extrabold items-center gap-3 text-base md:text-xl font-sofia">
            <img src={event.image} style={{width:"30px"}} className="w-5 h-5" />
            <div className="hidden md:flex items-center gap-2 w-full">
              <h1>{team1.name}</h1> vs <h1>{team2.name}</h1>
            </div>
            <span className="hidden md:inline !font-extrabold">
              {series_name}
            </span>
          </div>

          <div className="flex items-center gap-3 text-xs md:text-base font-bold font-sofia text-[#DBFAFF]">
            <span>{date}</span>
            <span>{time}</span>
            <button
              onClick={onClose}
              className="w-7 h-7 flex items-center justify-center rounded hover:bg-[#4B5563]"
              aria-label="Close modal"
            >
              <img src="/images/ui/cross.svg" alt="" />
            </button>
          </div>
        </div>

        <div className="max-h-[85vh] scrollbar-hide overflow-y-auto">
          <div className="px-4 md:px-6 py-4 flex flex-col gap-3">
            {/* Odds row */}
            <div className="flex flex-col md:flex-row gap-3 justify-center">
              <button
                onClick={() => {
                  setSelectedTeam("home");
                  setTeamId(team1.id);
                }}
                type="button"
                className={`
    flex font-onest text-xs md:text-base 2xl:text-lg 
    border-2 pl-5 justify-between gap-4 md:w-[400px]
    duration-300 cursor-pointer
    ${
      selectedTeam === "home"
        ? "border-[#4D4CFE] bg-[#2B5AFF26]"
        : "border-[#29313D] hover:border-[#4D4CFE] hover:bg-[#2B5AFF26]"
    }
  `}
              >
                <div className="flex items-center gap-2">
                  {/* <img src={team1.logo} alt={team1.name} style={{width:"40px"}}/> */}
                  <h1>{team1.name}</h1>
                </div>
                <div className="bg-[#13151A] p-2">
                  {team1_price} ¢
                </div>
              </button>

              <button
                onClick={() => {
                  setSelectedTeam("away");
                  setTeamId(team2.id);
                }}
                type="button"
                className={`
    flex font-onest text-xs md:text-base 2xl:text-lg 
    border-2 pr-5 justify-between gap-4 md:w-[400px]
    duration-300 cursor-pointer
    ${
      selectedTeam === "away"
        ? "border-[#4D4CFE] bg-[#2B5AFF26]"
        : "border-[#29313D] hover:border-[#4D4CFE] hover:bg-[#2B5AFF26]"
    }
  `}
              >
                <div className="bg-[#13151A] p-2">
                  {team2_price} ¢
                </div>
                <div className="flex items-center gap-2">
                  <h1>{team2.name}</h1>
                  {/* <img src={team2.logo} alt={team2.name} style={{width:"40px"}}/> */}
                </div>
              </button>
            </div>

            {/* Text summary */}
            <div className="mt-1 text-center text-base md:text-xl font-sofia text-[#54657E]">
              CHOOSE YOUR TEAM TO BET ON ABOVE
            </div>

            {/* Value/reward */}
            <div className="flex flex-col items-center">
              <div className="mt-3 w-[320px] md:w-90 text-sm md:text-base font-medium font-onest">
                <p className="flex items-center gap-2">
                  YOUR CARDS VALUE{" "}
                  <span className="font-bold flex items-center gap-1 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"
                      />
                    )}
                    {Number(totalValueLocal).toFixed(2)}
                  </span>
                </p>
                <p className="mt-1 flex gap-2">
                  POTENTIAL REWARD{" "}
                  <span className="font-bold flex items-center gap-1 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"
                      />
                    )}
                    {Number(totalValueLocal).toFixed(2)} × {bet_odd} =
                    <span className="text-[#F14B3F] flex items-center gap-1 ">
                      {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"
                        />
                      )}
                      
                      {win_price()}
                    </span>
                  </span>
                </p>
              </div>
            </div>

            {/* Selected cards preview */}
            {selectedIds.length > 0 && (
              <div className="border w-[320px] md:w-90 mx-auto border-[#54657E] bg-[#13151A] px-4 py-4 flex flex-col items-center gap-4">
                <div className="flex flex-wrap overflow-y-auto scrollbar-hide max-h-25 justify-center gap-3">
                  {selectedCards.map((card, ind) => (
                    <button
                      key={card.inv_id ?? ind}
                      type="button"
                      onClick={() => toggleSelect(card.inv_id)}
                      className="relative cursor-pointer bg-[#0B1120] border border-transparent hover:border-[#4D4CFE] duration-200"
                      title="Click to remove"
                    >
                      <img
                        src={card.image.replace("cardsimages", "cards/images")}
                        alt={card.name}
                        className="w-15 h-auto"
                      />

                      {/* optional little X badge */}
                      {/* <div className="absolute -top-2 -right-2 bg-[#13151A] border border-[#4D4CFE] text-white text-[10px] w-5 h-5 flex items-center justify-center">
                        ✕
                      </div> */}
                    </button>
                  ))}
                </div>

                <button
                  type="button"
                  disabled={betLoading}
                  onClick={() => {
                    if (!teamId) {
                      setModalType("error");
                      setModalMsg("Please select a team to place your bet.");
                      setModalOpen(true);
                      return;
                    } // show modal error etc.
                    handlePlaceBet(selectedCards.map((c) => c.inv_id));
                  }}
                  className="w-full bg-(--color-blue) cursor-pointer hover:bg-[#6366F1] text-white font-onest font-medium text-xs md:text-base py-3 text-center"
                >
                  {betLoading ? "PLACING BET..." : "PLACE BET"}
                </button>
              </div>
            )}

            {/* All cards grid */}
            <div
              ref={scrollRef}
              onScroll={handleScroll}
              className="mt-1 md:-mx-6 max-h-50 overflow-y-auto scrollbar-hide border-[#29313D] bg-[#121924] px-4 py-2"
            >
              {cardLoading ? (
                <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>
              ) : cardsError ? (
                <h1 className="text-center text-white text-sm md:text-2xl">
                  {cardsError}
                </h1>
              ) : (
                <>
                   {visibleCards.length < 1 ? (
                <div className="flex flex-col items-center justify-center py-16 text-center">
                  <p className="text-base md:text-3xl font-bold text-white mb-2">
                    Open your packs to get started
                  </p>
                  <p className="text-sm md:text-2xl text-[var(--color-slate)] max-w-md">
                    Once you open a pack, your inventory cards will appear here.
                  </p>
                </div>
              ) : (

                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-4">
                  {visibleCards?.map((card, ind) => {
                    const isSelected = selectedIds.includes(card.inv_id);
                    return (
                      <div
                        key={`${card.id}-${card.inv_id}`}
                        onClick={() => {
                          if (betLoading) return;
                          toggleSelect(card.inv_id);
                        }}
                        className={`relative cursor-pointer bg-[#1F1C26] px-3 pt-4 pb-2 border transition 
                      ${
                        isSelected
                          ? "border-[#4D4CFE] box-shadow-custom-inset"
                          : "border-transparent hover:border-[#4D4CFE]"
                      }`}
                        role="button"
                        tabIndex={0}
                      >
                        <div className="text-center mb-1">
                          <div className="font-sofia font-extrabold text-xs md:text-sm">
                            {card.name.split(" ").slice(0, 2).join(" ")}
                          </div>
                          {/* <div className="font-onest text-[11px] md:text-xs text-[#9CA3AF]">
                          {card.rarity}
                        </div> */}
                        </div>

                        <div className="flex justify-center mb-1">
                          <img
                            src={card.image.replace(
                              "cardsimages",
                              "cards/images",
                            )}
                            className="w-18 img-border-radius object-contain"
                            alt=""
                          />
                        </div>

                        <div className="text-center flex items-center justify-center gap-1 font-sofia text-[#4D4CFE] text-sm md:text-base">
                          {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"
                            />
                          )}
                          {card.price}
                        </div>

                        {isSelected && (
                          <div className="absolute bottom-0 left-0 bg-[var(--color-blue)] shadow-lg p-2">
                            <img src="/images/coinFlip/modal/tick.svg" alt="" />
                          </div>
                        )}
                      </div>
                    );
                  })}
                  {(cards?.length ?? 0) > 0 && (
                    <div className="col-span-full flex justify-center py-4">
                      {apiLoading ? (
                        <div className="w-7 h-7 border-4 border-white/20 border-t-white rounded-full animate-spin" />
                      ) : hasMore ? (
                        <p className="text-xs text-white/60">
                          Scroll to load more…
                        </p>
                      ) : (
                        <p className="text-xs text-white/40">
                          All items loaded
                        </p>
                      )}
                    </div>
                  )}
                </div>
              )}
                </>
              )}
            </div>
          </div>
        </div>
        <AlertModal
          open={modalOpen}
          type={modalType}
          message={modalMsg}
          onClose={() => {
            setModalOpen(false);

            if (modalType === "success") {
              setSelectedIds([]);
              setSelectedTeam(null);
              setTeamId("");
              setVisibleCount(STEP);
              if (scrollRef.current) scrollRef.current.scrollTop = 0;

              // close bet modal too
              // onClose();
            }
          }}
        />
      </div>
    </div>
  );
}
