import { User } from "@/constants/types";
import React, { useEffect, useMemo, useState } from "react";

interface CardItem {
  id: string;
  name: string;
  price: string; // e.g. "$20.00"
  series: string;
  image: string;
  quantity: number;
  rarity: string;
}

interface Card {
  id: number;
  image: string;
  selected: boolean;
}

interface ModalProps {
  card: CardItem | null;
  isOpen: boolean;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  selectedQuantity: number;
  onQuantityChange: (qty: number) => void;
  user: User;
}

const CardSelectionModal: React.FC<ModalProps> = ({
  card,
  isOpen,
  setIsOpen,
  selectedQuantity,
  onQuantityChange,
  user,
}) => {
  const [cards, setCards] = useState<Card[]>([]);

  // pricePerCard from card.price string like "$20.00"
  const pricePerCard = useMemo(() => {
    if (!card?.price) return 0;
    const numeric = Number(card.price.replace(/[^0-9.]/g, ""));
    return isNaN(numeric) ? 0 : numeric;
  }, [card]);

  // Build cards array based on card.quantity when modal opens or card changes
  useEffect(() => {
    if (!card || !isOpen) {
      setCards([]);
      return;
    }

    const totalQty = card.quantity ?? 0;

    // ✅ new: respect selectedQuantity exactly (0 means none selected)
    const initiallySelected = Math.min(selectedQuantity, totalQty);

    const newCards: Card[] = Array.from({ length: totalQty }, (_, i) => ({
      id: i + 1,
      image: card.image,
      selected: i < initiallySelected, // first N selected
    }));

    setCards(newCards);
  }, [card, isOpen]);

  // const selectedCount = cards.filter((c) => c.selected).length;
  const selectedCount = useMemo(
    () => cards.filter((c) => c.selected).length,
    [cards]
  );

  const totalPrice = selectedCount * pricePerCard;

  // const toggleCard = (id: number) => {

  //   setCards((prev) => {
  //     const updated = prev.map((c) =>
  //       c.id === id ? { ...c, selected: !c.selected } : c
  //     );
  //     const count = updated.filter((c) => c.selected).length;
  //     onQuantityChange(count); // ✅ only on user action
  //     return updated;
  //   });
  // };

  const toggleCard = (id: any) => {
    console.log("id", id);
    setCards((prev) =>
      prev.map((c) => (c.id === id.id ? { ...c, selected: !c.selected } : c))
    );
  };

  const selectAll = () => {
    setCards((prev) => prev.map((c) => ({ ...c, selected: true })));
  };

  const deselectAll = () => {
    setCards((prev) => prev.map((c) => ({ ...c, selected: false })));
  };

  useEffect(() => {
    if (!isOpen || !card) return;

    if (selectedCount !== selectedQuantity) {
      onQuantityChange(selectedCount);
    }
  }, [selectedCount, selectedQuantity, isOpen, card, onQuantityChange]);

  if (!isOpen || !card) return null;

  return (
    <div
      onClick={() => setIsOpen(false)}
      className="fixed inset-0 z-99999999 cursor-pointer flex items-center justify-center p-4 bg-black/60 bg-opacity-75  "
      // select-card-bg-shadow backdrop-blur-xs
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-3xl 2xl:max-w-5xl max-h-125 2xl:max-h-175 flex flex-col"
      >
        {/* Header */}
        <div className="px-3 md:px-6 py-2 md:py-4 flex items-center flex-col md:flex-row justify-between bg-(--color-naviBlue)">
          <div className="flex justify-between md:justify-start mb-3 md:mb-0 w-full md:w-auto items-center gap-4">
            <button
              onClick={() => setIsOpen(false)}
              className="cursor-pointer text-[10px] md:text-sm p-1.5 md:p-2 px-3 md:px-4 font-extrabold text-white bg-(--color-gray) hover:text-white italic font-sofia transition"
            >
              &lt; BACK
            </button>
            <div>
              <div className="text-xs font-sofia font-extrabold md:text-lg 2xl:text-2xl uppercase">
                <div className="flex items-center gap-2">
                  <span>{card.name}</span>
                  <span className="text-(--color-pink)">{card.rarity}</span>
                </div>
              </div>
              <div className="text-(--color-blue) font-bold">
                ${pricePerCard.toFixed(2)}
              </div>
              <div className="text-white flex items-center gap-2 font-semibold">
                Total:
                <span className="flex items-center gap-1">
                  {user?.activeMode === "coins" ? (
                    <img
                      src="/images/header/win.svg"
                      alt=""
                      className="h-3 w-3"
                    />
                  ) : (
                    <img
                      src="/images/header/star.svg"
                      alt=""
                      className="h-3 w-3"
                    />
                  )}
                  {totalPrice.toFixed(2)}
                </span>
              </div>
            </div>
          </div>

          <div className="hidden md:block text-white font-extrabold text-[10px] font-sofia md:text-base 2xl:text-2xl">
            {selectedCount} CARD{selectedCount !== 1 ? "S" : ""} SELECTED
          </div>

          <div className="md:flex hidden items-center gap-4">
            <button
              onClick={selectedCount === cards.length ? deselectAll : selectAll}
              className="px-3 md:px-4 py-1.5 md:py-2 bg-white text-(--color-blue) font-onest font-semibold text-[10px] md:text-sm 2xl:text-xl hover:bg-gray-100 transition-colors"
            >
              {selectedCount === cards.length ? "DESELECT ALL" : "SELECT ALL"}
            </button>
          </div>

          <div className="flex md:hidden items-end flex-row gap-3 md:gap-0 justify-between md:justify-end w-full md:flex-col">
            <div className="text-white font-extrabold text-sm font-sofia md:text-xl 2xl:text-2xl">
              {selectedCount} CARD{selectedCount !== 1 ? "S" : ""} SELECTED
            </div>
            <div className="flex items-center gap-4">
              <button
                onClick={
                  selectedCount === cards.length ? deselectAll : selectAll
                }
                className="px-3 md:px-4 py-1.5 md:py-2 bg-white text-(--color-blue) font-onest font-semibold text-[10px] md:text-base 2xl:text-xl hover:bg-gray-100 transition-colors"
              >
                {selectedCount === cards.length ? "DESELECT ALL" : "SELECT ALL"}
              </button>
            </div>
          </div>
        </div>

        {/* Cards Grid */}
        <div className="flex-1 overflow-y-auto nice-scrollbar py-6">
          <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-4 lg:grid-cols-6 gap-4">
            {cards.map((c) => (
              <div
                key={c.id}
                onClick={(e) => {
                  e.stopPropagation();
                  toggleCard(c);
                }}
                className={`relative cursor-pointer w-20 md:w-28 overflow-hidden transition-all duration-200 ${
                  c.selected
                    ? "ring-2 ring-(--color-blue) rounded"
                    : "opacity-80"
                }`}
              >
                <img
                  src={c.image.replace("cardsimages", "cards/images")}
                  alt={`Card ${c.id}`}
                  className="w-full h-auto object-contain img-border-radius"
                />
                {c.selected && (
                  <div className="absolute bottom-0 left-0 bg-(--color-blue) shadow-lg p-2 md:p-3.5">
                    <img src="/images/coinFlip/modal/tick.svg" alt="selected" />
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CardSelectionModal;
