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 type { LobbyMemberLeaveEventData } from "@/server/redis/events";
import { api } from "@/trpc/react";
import { useRouter } from "next/navigation";
import React from "react";

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();
  api.lobby.onMemberUpdate.useSubscription(undefined, {
    onData({ data: _data }) {
      const joined = _data.joined;
      if (joined) {
        const data = _data.membership as LobbyMember;
        addMember(data);
      } else {
        const data = _data.membership as LobbyMemberLeaveEventData;
        removeMember(data.playerId);
        if (data?.kicked && data?.playerId === sessionPlayer?.id) {
          router.push(appRoutes.lobby(lobby.id));
          router.refresh();
        }
      }
    },
  });

  api.lobby.onUpdate.useSubscription(undefined, {
    onData({ data }) {
      if (!data?.lobby) return;
      updateLobby(data.lobby);
    },
  });
  React.useEffect(() => {
    resetLobby(initialLobby);
    setMembers(initialLobby?.members ?? []);
  }, [initialLobby]);

  return children;
}

export default LobbyProvider;
