import { appRoutes } from "@/config/app.routes";
import { useSessionPlayerStore } from "@/lib/store/current-player-store";
import { useLobbyStore } from "@/lib/store/lobby-store";
import type { Lobby, LobbyMember } from "@/server/db/schema";
import { api } from "@/trpc/react";
import { useRouter } from "next/navigation";
import React from "react";
import { toast } from "sonner";

function LobbyProvider({
  children,
  initialLobby,
}: {
  children: React.ReactNode;
  initialLobby: Lobby;
}) {
  const sessionPlayer = useSessionPlayerStore((state) => state.sessionPlayer);
  const lobby = useLobbyStore((state) => state.lobby);
  const updateLobby = useLobbyStore((state) => state.updateLobby);
  const resetLobby = useLobbyStore((state) => state.resetLobby);
  const setMembers = useLobbyStore((state) => state.setMembers);
  const addMember = useLobbyStore((state) => state.addMember);
  const removeMember = useLobbyStore((state) => state.removeMember);

  const router = useRouter();

  const lobbyId = lobby.id ?? "";
  api.lobby.onMemberUpdate.useSubscription(
    { lobbyId },
    {
      onData({ data }) {
        if (data.joined) {
          const member = data.member as LobbyMember;
          addMember(member);
        } else {
          const memberId = data.member as string;
          removeMember(memberId);
          if (data?.kicked && memberId === sessionPlayer?.id) {
            router.push(appRoutes.lobby(lobby.id));
            router.refresh();
          }
        }
      },
    },
  );

  api.lobby.onUpdate.useSubscription(
    { lobbyId },
    {
      onData({ data }) {
        if (data.deleted) {
          resetLobby(undefined);
          router.push(appRoutes.home);
          router.refresh();
          toast.error("Lobby got deleted");
          return;
        }
        if (data.lobby) updateLobby(data.lobby);
      },
    },
  );
  React.useEffect(() => {
    resetLobby(initialLobby);
    setMembers(initialLobby?.members ?? []);
  }, [initialLobby]);

  return children;
}

export default LobbyProvider;
