import React, { useState, useEffect } from "react";
import TagJs from "./Tags.jsx";
import { API_URL, sendRequest } from "@/app/constants";

const CardPool = () => {
  const [pack, setPack] = useState("");
  const [tag, setTag] = useState("");
  const [value, setValue] = useState("");

  const [packs, setPacks] = useState([]);
  const [cards, setCards] = useState([]);
  const [Tags, setTags] = useState([]);
  const [minValue, setMinValue] = useState(0);
  const [maxValue, setMaxValue] = useState(100);
  const [isOpen, setIsOpen] = useState(false);
  const [isOpenTag, setIsOpenTag] = useState(false);
  const gameModules = [
    "aetherdrift",
    "archazias-island",
    "assassins",
    "azurite-sea",
    "bloomburrow",
    "chilling-reign",
    "commander-masters",
    "destined-rivals",
    "duskmourn-house-of-horror",
    "evolving-skies",
    "fusion-strike",
    "innistrad-remastered",
    "into-the-inklands",
    "journey-together",
    "march-of-the-machine",
    "outlaws-of-thunder-junction",
    "packwheel",
    "paldea-evolved",
    "paldean-fates",
    "phyrexia-all-will-be-one",
    "prismatic-evolutions",
    "ravnica-remastered",
    "reign-of-jafar",
    "rise-of-the-floodborn",
    "shimmering-skies",
    "surging-sparks",
    "sv-151",
    "the-first-chapter",
    "ursulas-return",
    "wilds-of-eldraine",
  ];

  const getTag = (data) => {
    let d = [];
    for (let n = 0; n < data.length; n++) {
      let exp = data[n].tag.split(",");
      data[n].tag = exp[0].trim();
      d.push(data[n]);
    }
    let uniqueMap = new Map();

    data.forEach((item) => {
      if (!uniqueMap.has(item.tag)) {
        uniqueMap.set(item.tag, {
          tag: item.tag,
          minRange: item.minRange,
          maxRange: item.maxRange,
        });
      }
    });

    let uniqueTags = Array.from(uniqueMap.values());
    setTags(uniqueTags);
  };

  const getValue = (v) => {
    let t = {};
    for (let f of Tags) {
      if (f.tag == v) {
        t = f;
      }
    }

    setTag(t?.tag);
    setMinValue(t.minRange);
    setMaxValue(t.maxRange);
  };

  useEffect(() => {
    if (pack != "" && tag != "" && value != "") {
      let _url = API_URL + `get_fairness_cards?t=${tag}&v=${value}&p=${pack}`;
      sendRequest({ method: "get", url: _url, body: {} }, null, (res) => {
        setCards(res);
      });
    } else {
      setCards([]);
    }
  }, [pack, tag, value]);

  useEffect(() => {
    sendRequest(
      {
        method: "GET",
        url: API_URL + "get_packs",
        body: { f: 1 },
      },
      null,
      (res) => {
        const filtered = res.filter((item) => gameModules.includes(item.slug));
        setPacks(filtered);
      },
    );
  }, []);

  return (
    <>
      <div className=" flex items-center font-onest justify-center  py-10 ">
        <div className="w-full max-w-3xl bg-(--color-naviBlue)  shadow-lg p-4 md:p-8 space-y-6 border border-(--color-gray)">
          {/* PACK SELECT */}
          <div>
            <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
              Pack
            </label>
            <div className="relative">
              <select
                value={pack}
                onChange={(e) => setPack(e.target.value)}
                onClick={() => setIsOpen(!isOpen)}
                className="w-full appearance-none bg-(--color-naviBlue)  border border-(--color-gray)  p-3 focus:outline-none  cursor-pointer overflow-y-auto no-scrollbar"
              >
                <option value="" className="bg-(--color-naviBlue) ">
                  Select Pack
                </option>
                {gameModules.map((p, i) => (
                  <option key={i} value={p} className="bg-(--color-naviBlue) ">
                    {p}
                  </option>
                ))}
              </select>
              <span
                className={`absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400 transition-transform duration-200 ${
                  isOpen ? "rotate-90" : "-rotate-90"
                }`}
              >
                &lt;
              </span>
            </div>
          </div>

          {/* TAG SELECT */}
          <div>
            <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
              Tag
            </label>
            <div className="relative">
              <select
                value={tag}
                onClick={() => setIsOpenTag(!isOpenTag)}
                onChange={(e) => getValue(e.target.value)}
                className="w-full appearance-none bg-(--color-naviBlue)  border border-(--color-gray)  p-3 focus:outline-none  cursor-pointer overflow-y-auto no-scrollbar"
              >
                <option value="" className="bg-(--color-naviBlue) ">
                  Select Tag
                </option>
                {Tags.map((item, i) =>
                  item.tag.toLowerCase().includes("category") ||
                  item.tag.toLowerCase().includes("slot") ||
                  item.tag.toLowerCase().includes("odds") ? null : (
                    <option
                      key={"tag" + i}
                      value={item.tag}
                      className="bg-(--color-naviBlue) "
                    >
                      {item.tag}
                    </option>
                  ),
                )}
              </select>
              <span
                className={`absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400 transition-transform duration-200 ${
                  isOpenTag ? "rotate-90" : "-rotate-90"
                }`}
              >
                &lt;
              </span>
            </div>
          </div>

          {/* VALUE INPUT */}
          <div>
            <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
              Value
            </label>
            <input
              type="number"
              value={value}
              min={0}
              max={maxValue}
              onChange={(e) => {
                const val = Number(e.target.value);
                if (val >= 0 && val <= maxValue) {
                  setValue(e.target.value);
                }
              }}
              placeholder={`Enter value (${minValue} - ${maxValue})`}
              className="w-full bg-(--color-naviBlue) border border-(--color-gray) p-3 focus:outline-none  no-spinner"
            />
          </div>

          {/* RESULT BOX */}
          <div className="border border-dotted border-(--color-gray)  p-8 flex items-center justify-center h-40 text-center text-gray-400">
            {cards.length > 0 ? (
              <div className="cards-cal">
                {cards.map((card, i) => (
                  <img
                    key={"card" + i}
                    src={`/cards/${card}`}
                    alt={`card-${i}`}
                    className="rounded"
                    style={{
                      height: "100px",
                      width: "auto",
                      objectFit: "contain",
                    }}
                  />
                ))}
              </div>
            ) : (
              <p className="font-sofia text-sm font-bold text-white md:text-2xl">
                More inputs are required to verify result
              </p>
            )}

            {/* {pack && tag && value
            ? `✅ ${pack} | ${tag} | Value: ${value}`
            : "More inputs are required to verify result"} */}
          </div>
        </div>
      </div>
      <TagJs pack={pack} getTag={getTag} />
    </>
  );
};

export default CardPool;
