"use client";
import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import "./style.css";
import { BASE_URL } from "@/constants";
import Anim from "../../../components/packAnim/Anim";
import { useSelector } from "react-redux";
import { clearSelectedPackCover } from "../../../store/inventorySlice";
import { useAppDispatch } from "../../../lib/hooks";

export default function Inner({ user_id, mode }) {
  const [isLoading, setIsLoading] = useState(true);
  const params = useParams();
  const [brand, setBrand] = useState("");
  const [packId, setPackId] = useState(0);
  const [pack, setPack] = useState({ id: null });
  const [cards, setCards] = useState([]);
  const user = useSelector((state) => state.auth.user);
  const selectedCover = useSelector(
    (state) => state.inventory.selectedPackCover,
  );
  const didRun = useRef(false);

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (selectedCover) {
      setPack((p) => ({ ...p, cover_image: selectedCover }));
      // dispatch(clearSelectedPackCover());
    }
  }, [selectedCover, dispatch]);

  useEffect(() => {
    if (didRun.current) return;
    didRun.current = true;

    setBrand(params.category);
    setPackId(params.pack);

    const brnd = params.category;
    const pk = params.pack;

    let brand_image = "";
    if (pk) {
      if (brnd == "Pokemon") {
        brand_image = "/assets/images/pokemon-brand.png";
      } else if (brnd == "MTG") {
        brand_image = "/assets/images/magic_back.webp";
      } else if (brnd == "Lorcana") {
        brand_image = "/assets/images/lorcana-back.png";
      }
      getCards(pk, user_id, brand_image);
    }
  }, [params.category, params.pack, user_id]);

  async function getCards(pack, user_id, brand_image) {
    setIsLoading(true);
    try {
      const res = await fetch(BASE_URL + "/api/get-anim", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${user.token}`,
        },
        body: JSON.stringify({
          user_id: user.userId,
          pack_id: pack,
        }),
      });

      const data = await res.json();
      if (data.resp == "success") {
        let c = data.cards;
        c = c.reverse();

        setCards(data.cards);
        let p = data.pack;
        p.brand_image = brand_image;
        setPack(p);
      } else if (data.resp == "error") {
        // window.location = "/inventory";
      }
    } catch (err) {
      console.error("Error:", err);
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <>
      {/* {isLoading ? (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm">
          <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>
        </div>
      ) : ( */}
      <>
        {/* {pack?.id ? ( */}
        <Anim
          user_id={user.userId}
          mode={"turn"}
          cards={cards}
          pack={pack}
          packId={packId}
          brand={brand}
        />
        {/* ) : (
          <div className="text-white text-center mt-5">No pack found</div>
        )} */}
      </>
      {/* )} */}
    </>
  );
}
