// JoinGamePanel.tsx
import React, { useState } from "react";
import Image from "next/image";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import AlertModal from "../ui/AlertModal";

type Tier = {
  id: string | number;
  name: string;
  image: string;
  playLabel: string;
  buttonClass: string;
};

type Player = {
  id: string | number;
  name: string;
  image?: string;
  totalValue: number;
  cards?: any[];
};

type JoinGamePanelProps = {
  tiers: Tier[];
  playersByTier: Record<string, Player[]>;

  userName: string;
  userImage?: string;

  setXvalue: (v: string) => void;
  setJoinModalOpen: (v: boolean) => void;

  joinedRef: React.MutableRefObject<Record<string, boolean>>;
  socketRef: React.MutableRefObject<any>; // ideally type your socket
  rollPhase: "countdown" | "break";
  betSubmittedRef: React.MutableRefObject<boolean>;
  reloadCards: () => void;
};

interface AuthState {
  user: User; // adjust type as needed
  status: string;
}
export default function JoinGamePanel({
  tiers,
  playersByTier,
  userName,
  userImage,
  setXvalue,
  setJoinModalOpen,
  joinedRef,
  socketRef,
  rollPhase,
  betSubmittedRef,
  reloadCards,
}: JoinGamePanelProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  return (
    <section className="border mt-5 border-[#29313D]">
      <p className="text-base md:text-2xl 2xl:text-4xl font-sofia border-b border-[#29313D] bg-[#121924] py-4 px-4 text-white font-bold uppercase">
        Join the game
      </p>

      <div className="p-5 bg-[#161E2A]">
        <div className="grid gap-4 md:gap-5 grid-cols-[repeat(auto-fit,minmax(260px,1fr))]">
          {tiers.map((tier) => (
            <div key={tier.id} className="flex flex-col overflow-hidden">
              {/* Tier header */}
              <div className="flex items-center justify-between px-4 py-3 md:px-5 md:py-4 border-b border-slate-800 bg-[#121924]">
                <div className="flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full">
                    <Image
                      src={tier.image}
                      alt="tier icon"
                      width={24}
                      height={24}
                      className="w-full h-full object-contain"
                    />
                  </div>
                </div>
                <span className="text-xs md:text-sm font-semibold font-onest text-white">
                  {tier.name}
                </span>
              </div>

              {/* Play button */}
              <button
                disabled={rollPhase !== "countdown"}
                onClick={() => {
                  if (!user) {
                    setModalType("error"); // or "login" if you have a custom type
                    setModalMsg("Please log in to play game.");
                    setModalOpen(true);
                    return;
                  }
                  if (rollPhase !== "countdown") return;

                  const tierKey = String(tier.id); // ✅ unique key (tier-2x, tier-2x-red, etc)

                  setXvalue(tierKey);

                  if (!joinedRef.current[tierKey]) {
                    joinedRef.current[tierKey] = true;
                  }

                  const socket = socketRef.current;
                  socket?.emit("joinGame", {
                    user_id: user.userId,
                    name: userName,
                    tier: tierKey,
                    image: userImage,
                  });
                  betSubmittedRef.current = false;
                  setJoinModalOpen(true);
                  reloadCards();
                }}
                className={` ${rollPhase !== "countdown" ? "opacity-50 cursor-not-allowed" : ""} ${tier.buttonClass} mt-3 mb-4 py-3 text-xs cursor-pointer font-onest md:text-sm font-semibold tracking-wide uppercase transition ${tier.buttonClass}`}
              >
                {tier.playLabel}
              </button>

              {/* Players */}
              <div className="px-3 pb-4 w-full space-y-3">
                {(playersByTier[String(tier.id)] ?? []).map((player) => {
                  console.log("player", player);
                  return (
                    <div
                      key={player.id}
                      className="flex flex-col gap-1.5 sm:flex-row sm:items-center"
                    >
                      <div className="flex flex-1 items-center gap-1.5 text-base md:text-lg 2xl:text-2xl italic font-sofia font-semibold tracking-wide text-slate-300 uppercase">
                        <span className="inline-flex h-4 w-4 items-center justify-center rounded-full">
                          <img
                            src={player?.image}
                            className="w-full h-full"
                            alt=""
                          />
                        </span>
                        {player.name}
                      </div>

                      <div className="mt-1 flex-1 w-full sm:mt-0 flex justify-end">
                        <h1 className="font-sofia flex items-center gap-2 italic text-base md:text-xl 2xl:text-3xl text-[#FF348D] font-bold">
                          {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"
                            />
                          )}
                          {player.totalValue.toFixed(2)}
                        </h1>
                      </div>
                      {(player as any).cards?.slice(0, 3).map((c: any) => (
                        <img
                          key={c.inv_id}
                          src={c.image.replace("cardsimages", "cards/images")}
                          className="h-5 w-5 rounded"
                          alt=""
                        />
                      ))}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
        <AlertModal
          open={modalOpen}
          type={modalType}
          message={modalMsg}
          onClose={() => setModalOpen(false)}
        />
      </div>
    </section>
  );
}
