import { User } from "@/constants/types";
import React from "react";
import { useSelector } from "react-redux";

type DefaultPhase =
  | "idle"
  | "accelerating"
  | "fast"
  | "slow"
  | "slower"
  | "slowest"
  | "stopping"
  | "showWinners";

type BaseCard = {
  id: string | number; // <-- IMPORTANT: supports both
  name: string;
  image: string;
  price?: number;
};

export type CardTrackProps<
  TCard extends BaseCard = BaseCard,
  TPhase extends string = DefaultPhase,
> = {
  trackRef: React.RefObject<HTMLDivElement | null>; // <-- allow null
  cardRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;
  track: TCard[];
  phase: TPhase; // <-- accepts your parent union
  offset: number;
  segWidth: number;
  centerIndex: number | null; // <-- allow null
  targetIndices: number[];
  getAnimationClass: () => string;
};

export function CardTrack<
  TCard extends BaseCard = BaseCard,
  TPhase extends string = DefaultPhase,
>({
  trackRef,
  cardRefs,
  track,
  phase,
  offset,
  segWidth,
  centerIndex,
  targetIndices,
  getAnimationClass,
}: CardTrackProps<TCard, TPhase>) {
  const user = useSelector((state: any) => state.auth.user) as User | null;

  return (
    <div
      ref={trackRef}
      className={`flex items-center gap-4 will-change-transform ${getAnimationClass()}`}
      style={
        phase === ("stopping" as TPhase) || phase === ("showWinners" as TPhase)
          ? {
              transform: `translateX(${offset}px)`,
              transition: "transform 1s cubic-bezier(0.22, 0.61, 0.36, 1)",
            }
          : phase !== ("idle" as TPhase)
            ? ({ ["--seg" as any]: `${-segWidth}px` } as React.CSSProperties)
            : {}
      }
    >
      {track.map((card, i) => {
        const isWinner =
          (phase === ("stopping" as TPhase) ||
            phase === ("showWinners" as TPhase)) &&
          targetIndices.includes(i);

        const shouldHide = phase === ("showWinners" as TPhase) && !isWinner;

        return (
          <div
            key={`${card.id}-${i}`}
            ref={(el) => {
              cardRefs.current[i] = el;
            }}
            className={`
              min-w-32 min-h-44 shrink-0 flex mt-5 flex-col 
              items-center justify-center 
              transition-all duration-300
              ${centerIndex === i ? "center-zoom " : "center-normal "}
              ${shouldHide ? "opacity-0" : "opacity-100"}
            `}
          >
            <img
              src={`/cards${
                card.image?.startsWith("/") ? card.image : `/${card.image}`
              }`}
              alt={card.name}
              className={`w-20 md:w-24 md:h-36
                transition-transform duration-300 object-contain ease-out ${
                  isWinner ? "scale-110" : "opacity-100"
                }`}
            />

            {phase === ("showWinners" as TPhase) && isWinner && (
              <div className="text-center mt-3 animate-fadeIn">
                <h3 className="text-sm font-bold text-white">{card.name}</h3>
                <p className="text-lg flex justify-center items-center gap-1 font-extrabold text-[#FF0080]">
                  {!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"
                        />
                      )}
                    </>
                  )}
                  {card.price ?? 0}
                </p>
                {/* <p className="text-xs text-white/80 -mt-1">
                  trackIndex: {i} | baseIndex:{" "}
                  {track.length
                    ? i %
                      (track.length
                        ? (track as any[]).filter(() => true).length
                        : 1)
                    : 0}
                </p> */}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
