"use client";

import React from "react";
import type { Lobby } from "@/server/db/schema";
import LobbyPlayerCard from "@/app/_components/lobby/lobby-player/player-card";
import LobbyMembershipDialog from "@/app/_components/lobby/lobby-membership-dialog";
import { Badge } from "@/components/ui/badge";
import CopyToClip from "@/components/copy-to-clip";
import { appRoutes } from "@/config/app.routes";
import LobbySettingsDialog from "./lobby-settings-dialog";
import { getBaseUrl } from "@/lib/utils";
import GameSelector from "./game-selector";
import LobbyProvider from "./lobby-provider";
import { useSessionPlayerStore } from "@/lib/store/current-player-store";
import { useLobbyStore } from "@/lib/store/lobby-store";
import { Share2, UserPlus } from "lucide-react";

function LobbyPage({ initialLobby }: { initialLobby: Lobby }) {
  const sessionPlayer = useSessionPlayerStore((state) => state.sessionPlayer);
  const lobby = useLobbyStore((state) => state.lobby);
  const members = useLobbyStore((state) => state.members);
  const isJoined = sessionPlayer
    ? members.find((m) => m.playerId === sessionPlayer.id)
    : null;

  const isAdmin = isJoined?.role === "admin";

  return (
    <LobbyProvider initialLobby={initialLobby}>
      <div className="grid max-w-4xl grid-cols-3 grid-rows-2 gap-4">
        <div className="container-bg col-span-2 w-full space-y-4 p-6">
          <div className="flex items-center gap-2">
            <CopyToClip
              target="invite link"
              text={getBaseUrl() + appRoutes.lobby(lobby.id)}
              buttonProps={{ variant: "outline" }}
            >
              {isJoined ? (
                <>
                  <UserPlus className="size-4" />
                  <span>Invite Players</span>
                </>
              ) : (
                <>
                  <Share2 className="size-4" />
                  <span>Share Lobby</span>
                </>
              )}
            </CopyToClip>

            <div className="ml-auto">
              {sessionPlayer && (
                <LobbyMembershipDialog lobbyId={lobby.id} join={!isJoined} />
              )}
            </div>
          </div>
          <div className="flex w-full items-center justify-between text-nowrap">
            <h1 className="w-full overflow-hidden text-2xl font-bold text-ellipsis">
              {lobby.name}
            </h1>
            {isAdmin && <LobbySettingsDialog lobby={lobby} />}
          </div>
          <div className="border-border/20 flex items-center justify-between border-b pb-4">
            <h2 className="text-sm font-medium">
              Players ({members?.length || 0}/{lobby.maxPlayers || 8})
            </h2>
            <span className="text-xs">
              {members?.length === (lobby.maxPlayers || 8)
                ? "Lobby Full"
                : "Waiting..."}
            </span>
          </div>

          <ul className="space-y-2">
            {members?.map((member, idx) => (
              <li key={idx}>
                <LobbyPlayerCard
                  lobbyId={lobby.id}
                  highlight={member?.player?.id === sessionPlayer?.id}
                  player={member?.player!}
                  className="relative"
                  showOptions={
                    isAdmin && member?.playerId !== sessionPlayer?.id
                  }
                >
                  {member?.role === "admin" && (
                    <Badge className="absolute -top-2 right-2 z-20 p-px px-2 text-white">
                      Admin
                    </Badge>
                  )}
                </LobbyPlayerCard>
              </li>
            ))}
          </ul>
        </div>
        <div className="container-bg col-span-1 size-full"></div>
        <div className="col-span-3">
          <GameSelector />
        </div>
      </div>
    </LobbyProvider>
  );
}

export default LobbyPage;
