"use client";
import React, { useEffect, useMemo, useState } from "react";
import type { ChaseSlab } from "./types";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { SlabAnalytics } from "@/app/games/mystery-packs/Inner";

export default function ChaseSlabsGrid({
  slabs,
  slabAnalytics,
  slabLoading,
}: {
  slabs: ChaseSlab[];
  slabAnalytics: SlabAnalytics;
  slabLoading: boolean;
}) {
  // ✅ pagination
  const [page, setPage] = useState(1);
  const pageSize = 10;

  const cards = slabAnalytics?.cards ?? [];
  const totalPages = Math.ceil(cards.length / pageSize) || 1;

  useEffect(() => {
    // ✅ reset page when data changes
    setPage(1);
  }, [cards.length]);

  const paginatedCards = useMemo(() => {
    const start = (page - 1) * pageSize;
    const end = page * pageSize;
    return cards.slice(start, end);
  }, [cards, page, pageSize]);

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };
  const user = useSelector((state: any) => state.auth.user) as User | null;

  return (
    <>
      {slabLoading ? (
        <div className="flex w-full h-20 items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      ) : (
        <>
          {slabAnalytics?.cards?.length < 1 ? (
            <>
              <h1 className="text-center">No data found</h1>
            </>
          ) : (
            <div className="grid gap-4 grid-cols-2 sm:grid-cols-4 lg:grid-cols-5">
              {paginatedCards.map((s: any, index: number) => (
                <div key={index} className="mt-2">
                  <div className=" flex items-center justify-center">
                    <img
                      // src="/images/mystery-packs/chaseSlab.svg"
                      src={s.cover_image?.replace(/\\/g, "")}
                      alt="img"
                      className="w-24 object-contain"
                    />
                  </div>

                  <div className="mt-3">
                    <p className="text-xs text-[#8F8F8F] font-extrabold text-center uppercase">
                      {s.card_title} {slabAnalytics.cards.length}
                    </p>

                    <div className="mt-1 flex items-center justify-center gap-2 text-xs text-[#DBFAFF]">
                      <span className="flex items-center gap-2">
                        {!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"
                              />
                            )}
                          </>
                        )}
                        {s?.price.toLocaleString()}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {/* ✅ same pagination UI */}
          {totalPages > 1 && (
            <div className="flex font-onest justify-center items-center gap-3 m-6">
              <button
                onClick={() => goToPage(page - 1)}
                disabled={page === 1}
                className="rounded-full md:w-[34px] md:h-[34px] flex justify-center items-center bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
              >
                <img src="/images/profile/left.svg" alt="" />
              </button>

              <div className="flex gap-2 text-sm">
                {[...Array(totalPages)].map((_, i) => {
                  const pg = i + 1;

                  // show only first, last, current, and neighbors
                  if (
                    pg === 1 ||
                    pg === totalPages ||
                    Math.abs(pg - page) <= 1
                  ) {
                    return (
                      <button
                        key={pg}
                        onClick={() => goToPage(pg)}
                        className={`px-3 py-1 rounded ${
                          pg === page
                            ? "scale-115 text-white"
                            : "text-[var(--color-naturalGray)]"
                        }`}
                      >
                        {pg}
                      </button>
                    );
                  }

                  // ellipsis
                  if (pg === page - 2 || pg === page + 2) {
                    return (
                      <span
                        key={`ellipsis-${pg}`}
                        className="px-2 text-gray-400"
                      >
                        ...
                      </span>
                    );
                  }

                  return null;
                })}
              </div>

              <button
                onClick={() => goToPage(page + 1)}
                disabled={page === totalPages}
                className="flex justify-center items-center md:w-[34px] md:h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
              >
                <img src="/images/profile/right.svg" alt="" />
              </button>
            </div>
          )}
        </>
      )}
    </>
  );
}
