"use client";

import { useMemo, useState } from "react";

import { IGetChatsListResponse } from "@/entities/chats/types";
import { useAudioContext } from "@/providers/audio-provider";

import { useSocketEvent } from "../socket/useSocketEvent";

export interface UseChatsSocketOptions {
  initialChats?: IGetChatsListResponse;
  enableNotificationSound?: boolean;
}

export const useChatsSocket = (options: UseChatsSocketOptions = {}) => {
  const initialChats = options.initialChats ?? {
    categorizedChats: {},
    startedChats: [],
    unreadChats: [],
    totalUnreadCount: 0,
  };

  const { playNewMessageNotification } = useAudioContext();

  const [isInChat, setIsInChat] = useState(false);
  const [chats, setChats] = useState<IGetChatsListResponse>(initialChats);
  const [unreadCount, setUnreadCount] = useState<number>(
    initialChats.totalUnreadCount
  );

  useSocketEvent("chat_joined", () => setIsInChat(true));
  useSocketEvent("chat_left", () => setIsInChat(false));

  useSocketEvent("chats_updated", chats => setChats(chats));
  useSocketEvent("unread_messages_count", count =>
    setUnreadCount(prev => {
      if (!isInChat && prev < count.unreadCount) {
        playNewMessageNotification();
      }
      return count.unreadCount;
    })
  );

  return useMemo(
    () => ({
      chats,
      unreadChats: chats.unreadChats,
      startedChats: chats.startedChats,
      categorizedChats: chats.categorizedChats,
      totalUnreadCount: unreadCount,
      isInChat,
    }),
    [chats, unreadCount, isInChat]
  );
};
