"use client";

import { appRoutes } from "@/config/app.routes";
import type { Lobby, LobbyMember, Player } 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";

export function useRealtimeLobby({
  initialLobby,
  sessionPlayer,
}: {
  initialLobby: Lobby;
  sessionPlayer?: Player | null;
}) {
  const [lobby, setLobby] = React.useState(initialLobby);
  const [members, setMembers] = React.useState<Array<LobbyMember>>(
    initialLobby?.members ?? [],
  );
  const router = useRouter();
  api.lobby.onMemberUpdate.useSubscription(undefined, {
    onData({ data: _data }) {
      const joined = _data.joined;
      if (joined) {
        const data = _data.membership as LobbyMember;

        setMembers((prev) => {
          if (prev.find((m) => m.playerId === data.playerId)) return prev;
          return [...prev, data];
        });
      } else {
        const data = _data.membership as LobbyMemberLeaveEventData;
        setMembers((prev) => prev.filter((m) => m.playerId !== 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;
      setLobby((prev) => ({ ...data.lobby, members: prev.members }));
    },
  });
  return { lobby, members };
}
