import { useState, useEffect } from "react";
import LoaderJs from "./LoaderJs";
import { sendRequest, API_URL, API_BASE_URL } from "../../constants/index";

const Calculation = ({ paramsData }) => {
  const [pack, setPack] = useState("");
  const [serverSeed, setServerSeed] = useState("");
  const [clientSeed, setClientSeed] = useState("");
  const [nonce, setNonce] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [brand, setBrand] = useState();
  const [packs, setPacks] = useState([]);
  const [cards, setCards] = useState([]);

  // const { serverSeed, clientSeed, nonce } = paramsData;

  const gameModules = [
    "Aetherdrift",
    "SV 151",
    "Surging Sparks",
    "Archazias Island",
    "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",
    "Paldea Evolved",
    "Paldean Fates",
    "Phyrexia All Will Be One",
    "Prismatic Evolutions",
    "Mega Evolutions",
    "White Flare",
    "Black Bolt",
  ];

  const getResult = (data) => {
    let _url =
      pack === "PackWheel"
        ? API_URL +
          `get_fairness_cards?c=${JSON.stringify(
            data,
          )}&p=${pack}&brand=${brand}`
        : API_URL + `get_fairness_cards?c=${JSON.stringify(data)}&p=${pack}`;
    sendRequest({ method: "get", url: _url, body: {} }, null, (res) => {
      setCards(res);
    });
  };

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const seed = params.get("s");

    if (seed) {
      const p = params.get("p") || "";
      const c = params.get("c") || "";
      const n = params.get("n") || "";
      setPack(p);
      setServerSeed(seed);
      setClientSeed(params.get("c"));
      setNonce(params.get("n"));

      const _url =
        API_URL +
        `get_fairness_cards?c=${params.get(
          "c",
        )}&p=${p}&s=${seed}&n=${params.get("n")}`;
      sendRequest({ method: "get", url: _url, body: {} }, null, (res) => {
        setCards(res);
      });
    }

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

  useEffect(() => {
    if (!paramsData) return;
    setServerSeed(paramsData.serverSeed ?? "");
    setClientSeed(paramsData.clientSeed ?? "");
    setNonce(String(paramsData.nonce ?? ""));
  }, [paramsData]);

  const getCardUrl = (card) => {
    if (!card) return "";

    // full URL hai to wahi use karo
    if (card.startsWith("http://") || card.startsWith("https://")) {
      return card;
    }

    // leading slashes hatao
    let cleanPath = card.replace(/^\/+/, "");

    // ensure path /cards se start ho
    if (!cleanPath.startsWith("cards/")) {
      cleanPath = "cards/" + cleanPath;
    }

    return `${API_BASE_URL}${cleanPath}`;
  };

  return (
    <div className=" flex items-center font-onest py-10 justify-center  ">
      <div className="w-full max-w-3xl  bg-(--color-naviBlue)  shadow-lg p-4 md:p-8 space-y-6 border border-(--color-gray)">
        <div>
          <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
            Pack
          </label>
          <div className="relative">
            <select
              value={pack}
              onClick={() => setIsOpen(!isOpen)}
              onChange={(e) => {
                setPack(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-gray) ">
                Select Pack
              </option>
              {gameModules.map((p, i) => (
                <option key={i} value={p} className=" bg-(--color-gray) ">
                  {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>

        <div>
          <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
            Server Seed
          </label>
          <input
            type="text"
            value={serverSeed}
            onChange={(e) => setServerSeed(e.target.value)}
            placeholder="Enter Server Seed"
            className="w-full bg-transparent border border-(--color-gray)  p-3 focus:outline-none "
          />
        </div>

        <div>
          <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
            Client Seed
          </label>
          <input
            type="text"
            value={clientSeed}
            onChange={(e) => setClientSeed(e.target.value)}
            placeholder="Enter Client Seed"
            className="w-full bg-transparent border border-(--color-gray)  p-3 focus:outline-none "
          />
        </div>

        <div>
          <label className="block font-semibold mb-2 font-sofia text-sm md:text-xl">
            Nonce
          </label>
          <input
            type="text"
            value={nonce}
            onChange={(e) => setNonce(e.target.value)}
            placeholder="Enter Nonce"
            className="w-full bg-transparent border border-(--color-gray)  p-3 focus:outline-none "
          />
        </div>

        <div
          style={{ minHeight: "200px" }}
          className="border border-dotted border-(--color-gray)  p-8 flex items-center justify-center text-center "
        >
          {cards.length > 0 ? (
            <div className="grid grid-cols-3 md:grid-cols-6 gap-3 md:gap-4">
              {cards.map((card, i) => (
                <img
                  key={"card" + i}
                  src={`/cards/${card}`}
                  className="rounded"
                />
              ))}
            </div>
          ) : (
            <p className="font-sofia text-sm font-bold text-white md:text-2xl">
              More inputs are required to verify result
            </p>
          )}
        </div>

        <LoaderJs
          pack={pack}
          serverSeed={serverSeed}
          clientSeed={clientSeed}
          nonce={nonce}
          brand={brand}
          getResult={getResult}
        />
      </div>
    </div>
  );
};

export default Calculation;
