"use client";

import React, { useEffect, useRef, useState } from "react";
import { fetchPacksHistory, getPackCards } from "@/app/lib/api/profile";

interface PackItem {
  id: number | string;
  date: string;
  title: string;
  price: string;
  label: string;
  image: string;

  // ✅ fairness fields
  clientSeed?: string;
  serverSeed?: string;
  nonce?: string;
  cards?: string[]; // backend cards images (if available)
  totalCards?: number;
}

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { JourneyModal } from "./JournalModal";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}
type JourneyData = {
  title: string;
  totalCards: number;
  clientSeed: string;
  serverSeed: string;
  nonce: string;
  date: string;
  cards: string[];
};


export type packCard = {
  id:number;
  name:string;
  price:string;
  image:string;
}

const pageSize = 8; // 8 per page like before

const Packs: React.FC = () => {
  const [packs, setPacks] = useState<PackItem[]>([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [shipped, setShipped] = useState(0);
  const [shipment, setShipment] = useState(0);
  const [total, setTotal] = useState(0);
  const [isJourneyOpen, setIsJourneyOpen] = useState(false);
  const [fairnessData, setFairnessData] = useState<JourneyData | null>(null);
  const [packCards, setPackCard] = useState<packCard[]>([]);
  const hasFetched = useRef(false); // prevent double call in StrictMode

  const totalPages = Math.ceil(packs.length / pageSize) || 1;
  const paginatedData = packs.slice((page - 1) * pageSize, page * pageSize);

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  useEffect(() => {
    const loadPacks = async () => {
      if (hasFetched.current) return;
      hasFetched.current = true;

      try {
        setLoading(true);
        setError(null);

        const json = await fetchPacksHistory(user.userId, user.token, 0);

        if (json.resp !== "success") {
          throw new Error("Backend responded with error");
        }

        const data = json.data;

        setShipped(data.shipped ?? 0);
        setShipment(data.shipment ?? 0);
        setTotal(data.total ?? 0);

        // Map backend history → UI shape
        const mapped: PackItem[] = (data.history || []).map((h: any) => ({
          id: h.id,
          date: h.date,
          title: h.title || h.data_type || "PACK OPENED",
          price: h.amount || "$0",
          label: "FAIRNESS",
          image: h.image
            ? h.image.startsWith("/")
              ? h.image
              : `/${h.image}`
            : "/images/profile/img1.svg",

          // ✅ fairness values
          clientSeed: h.clientSeed ?? "",
          serverSeed: h.serverSeed ?? "",
          nonce: h.nonce ?? "",
          cards: Array.isArray(h.cards) ? h.cards : [],
          totalCards: Number(h.totalCards ?? 0),
        }));

        setPacks(mapped);
        setPage(1);
      } catch (err: any) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    };

    loadPacks();
  }, []);

  const fetchPackCards = async (packId: any) => {
    if (!packId) {
      console.error("packId is missing");
      return;
    }

    try {
      const res = await getPackCards(user.userId, user.token, packId);
      setPackCard(res.data ?? []);
    } catch (e: any) {
      console.log(e);
    }
  };

  const getPackImage = (image?: string | null) => {
    if (!image || image === "/" || image.trim() === "") {
      return "/cards/images/packs/aetherdrift.png";
    }

    // agar already absolute path ho
    if (image.startsWith("/")) {
      return `/cards${image}`;
    }

    return `/cards/${image}`;
  };

  return (
    <div className="border border-(--color-gray) px-3 text-white font-onest">
      {loading && (
        <div className="flex w-full h-40 items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      )}

      {error && (
        <div className="py-6 text-center text-sm text-red-400">{error}</div>
      )}

      {!loading && !error && packs.length === 0 && (
        <div className="py-6 text-center text-sm text-gray-300">
          No packs history yet.
        </div>
      )}

      {!loading && !error && packs.length > 0 && (
        <>
          {/* Grid of packs */}
          <div
            className="grid gap-2 py-2 md:py-4
                      sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 
                      xl:grid-cols-5 2xl:grid-cols-7"
          >
            {paginatedData.map((pack, index) => (
              <div
                key={index}
                className="bg-(--color-naviBlue) flex flex-col items-center text-center"
              >
                {/* Date strip */}
                <div className="w-full py-2 text-[10px] md:text-xs uppercase font-sofia font-semibold bg-(--color-darkBlue)">
                  {pack.date}
                </div>

                {/* Image */}
                <div className="w-full px-4 pt-3 pb-3 flex justify-center">
                  <img
                    src={getPackImage(pack.image)}
                    alt={pack.title}
                    className="max-h-52.5 w-auto object-contain"
                  />
                </div>

                <div className="bg-blur relative w-full z-10 px-3 -mt-7 pb-4 pt-3 text-center">
                  {/* Title */}
                  <div className="w-full px-3 font-sofia text-[11px] md:text-sm font-normal uppercase tracking-[0.16em] mb-1">
                    {pack.title.split(" ").slice(0, 2).join(" ") +
                      (pack.title.split(" ").length > 2 ? "..." : "")}
                  </div>

                  {/* Price */}
                  <div className="w-full px-3 flex items-center gap-1 justify-center font-sofia text-sm md:text-base font-extrabold mb-3">
                    {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"
                      />
                    )}
                    {pack.price.replace("$", "")}
                  </div>

                  {/* Button */}
                  <div className="w-full">
                    <button
                      onClick={() => {
                        const dummy = "/images/profile/pkimg.svg";
                        fetchPackCards(pack.id);
                        console.log("pack obj", pack);
                        // backend cards (if any) -> normalize paths
                        const cardsFromApi = (pack.cards ?? [])
                          .filter(Boolean)
                          .map((src) =>
                            src.startsWith("/") ? src : `/${src}`,
                          );

                        const finalCards = cardsFromApi.length
                          ? cardsFromApi
                          : Array(30).fill(dummy);

                        setFairnessData({
                          title: pack.title,
                          totalCards:
                            pack.totalCards && pack.totalCards > 0
                              ? pack.totalCards
                              : finalCards.length,
                          clientSeed: pack.clientSeed ?? "",
                          serverSeed: pack.serverSeed ?? "",
                          nonce: pack.nonce ?? "",
                          date: pack.date,
                          cards: finalCards,
                        });

                        setIsJourneyOpen(true);
                      }}
                      className=" px-3 md:px-5 !w-fit py-2 2xl:py-3 text-[10px] md:text-xs font-semibold uppercase tracking-[0.12em] bg-[var(--color-primaryBlue)] text-[var(--color-blue)] hover:bg-[var(--color-gray)] transition"
                    >
                      {pack.label}
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          <div className="flex font-onest justify-center items-center gap-3 m-6">
            <button
              onClick={() => goToPage(page - 1)}
              disabled={page === 1}
              className="rounded-full w-[34px] 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="Previous" />
            </button>

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

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

                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 w-[34px] h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
            >
              <img src="/images/profile/right.svg" alt="Next" />
            </button>
          </div>
        </>
      )}
      <JourneyModal
        open={isJourneyOpen}
        setOpen={setIsJourneyOpen}
        data={
          fairnessData ?? {
            title: "PACK",
            totalCards: 0,
            clientSeed: "",
            serverSeed: "",
            nonce: "",
            date: "",
            cards: Array(30).fill("/images/profile/pkimg.svg"),
          }
        }
        packCards={packCards}
      />
    </div>
  );
};

export default Packs;
