"use client";

import { User } from "@/constants/types";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import NotAvailable from "../components/ui/NotAvailable";
import { useEffect, useRef, useState } from "react";
import { fetchSpinPrices } from "../lib/api/spin";

type BoxItem = {
  id: number;
  slug: string;
  name: string;
  image: string;
};

const boxes: BoxItem[] = [
  {
    id: 1,
    slug: "og-box",
    name: "TCGWIN OG BOX",
    image: "/images/mystery-bozes/blue.svg",
  },
  {
    id: 2,
    slug: "fyre-box",
    name: "FYREBOX",
    image: "/images/mystery-bozes/yellow.svg",
  },
  {
    id: 3,
    slug: "ice-cold",
    name: "ICECOLD",
    image: "/images/mystery-bozes/lightBlue.svg",
  },
  {
    id: 4,
    slug: "silver-box",
    name: "SILVERBOX",
    image: "/images/mystery-bozes/img.svg",
  },
  {
    id: 5,
    slug: "ice-cold-1",
    name: "ICECOLD",
    image: "/images/mystery-bozes/lightBlue.svg",
  },
  {
    id: 6,
    slug: "silver-box-1",
    name: "SILVERBOX",
    image: "/images/mystery-bozes/img.svg",
  },
];

const Inner = () => {
  const router = useRouter();
  const user = useSelector((state: any) => state.auth.user) as User | null;
  // 3) Inner() ke andar ADD karo (router/user ke baad)
  type SpinPrices = Record<string, string | number>;
  const [spinPrices, setSpinPrices] = useState<SpinPrices>({});
  const [isPriceLoading, setIsPriceLoading] = useState(false);
  const isRun = useRef(false);

  const getSpinPrices = async () => {
    setIsPriceLoading(true);
    try {
      const res = await fetchSpinPrices();
      const prices = (res?.data ?? res) as SpinPrices; // res format ke hisaab se
      setSpinPrices(prices || {});
      setIsPriceLoading(false);
    } catch (e: any) {
      console.log(e);
    } finally {
      setIsPriceLoading(false);
    }
  };

  useEffect(() => {
    if (isRun.current) return;
    isRun.current = true;
    getSpinPrices();
  }, []);
  return (
    <div className="min-h-screen bg-black text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <div className=" z-10">
          <div className="container mx-auto py-4">
            <div className="bg-[#161E2A] relative overflow-hidden scrollbar-hide p-5 mt-4 flex items-center flex-col md:flex-row gap-4 justify-between w-full">
              <div className=" flex flex-col gap-3">
                <h1 className="italic text-base !font-extrabold font-sofia md:text-3xl">
                  MYSTERY BOXES
                </h1>
                <p className="max-w-[320px] tracking-tight leading-7 font-onest font-normal text-sm md:text-lg 2xl:text-2xl">
                  Choose packs from different price levels & unpack mystery
                  slabs
                </p>
              </div>

              <div className="flex relative -mb-14 items-center">
                <div className="absolute bottom-0 left-0 -translate-x-1/2 w-37.5 md:w-222.5 h-50 md:h-62.5 bg-[#FF348D] blur-3xl rounded-full opacity-50"></div>
                <img
                  src="/images/mystery-bozes/img.svg"
                  className=" object-contain relative z-20 "
                  alt=""
                />
              </div>
            </div>
            <div className="grid grid-cols-1 mt-5 gap-4 sm:grid-cols-2">
              {boxes.map((box) => (
                <article
                  key={box.id}
                  className="flex h-full flex-col overflow-hidden bg-[#071425] shadow-sm"
                >
                  {/* Image area */}
                  <div className="relative flex flex-1 items-center justify-center pt-4 -mb-6">
                    <div className="relative w-full max-w-xs">
                      <Image
                        src={box.image}
                        alt={box.name}
                        width={500}
                        height={400}
                        className="h-auto w-full object-contain"
                        priority={box.id === 1}
                      />
                    </div>
                  </div>

                  {/* Bottom bar */}
                  <div className="flex items-center relative bg-blur z-10 justify-between gap-3 bg-[#121924] px-4 py-3 sm:px-5 sm:py-4">
                    <div className="flex flex-col gap-1">
                      <span className="text-xs md:text-xl 2xl:text-2xl font-bold font-sofia sm:text-sm">
                        {box.name}
                      </span>
                      <span className="text-[11px] flex items-center gap-2 font-sofia font-medium -mt-2 md:text-base 2xl:text-lg sm:text-xs">
                        {!user ? (
                          <img
                            src="/images/header/win.svg"
                            alt=""
                            className="h-4 w-4"
                          />
                        ) : (
                          <>
                            {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"
                              />
                            )}
                          </>
                        )}
                        {isPriceLoading ? (
                          "loading..."
                        ) : (
                          <>{spinPrices?.[box.slug] ?? "--"}</>
                        )}
                      </span>
                    </div>

                    <button
                      onClick={() =>
                        router.push(`/games/spin/?boxId=${box.id}`)
                      }
                      className="whitespace-nowrap font-onest text-[#DBFAFF] bg-[#2B5AFF26] px-3 py-1.5 md:py-2 text-[10px] font-medium uppercase transition hover:bg-[#102547] sm:px-4 sm:text-xs"
                    >
                      Open Now!
                    </button>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Inner;
