import { useCallback } from 'react';
import { useSetAtom } from 'jotai';
import { MatrixClient } from 'matrix-js-sdk';
import { markAsRead } from '../utils/notifications';
import { roomToUnreadAtom } from '../state/room/roomToUnread';

/**
 * Hook that marks a room as read and immediately updates local unread state.
 * This fixes the issue where unread dots persist after refresh because the
 * server hasn't processed the read receipt yet.
 *
 * @param mx - Matrix client instance
 * @returns A function to mark rooms as read
 */
export function useMarkAsRead(mx: MatrixClient) {
  const setUnreadAtom = useSetAtom(roomToUnreadAtom);

  return useCallback(
    async (roomId: string, privateReceipt: boolean) => {
      // Immediately clear local unread state so UI updates instantly
      setUnreadAtom({ type: 'DELETE', roomId });

      // Then send the read receipt to the server
      await markAsRead(mx, roomId, privateReceipt);
    },
    [mx, setUnreadAtom]
  );
}

/**
 * Hook that marks multiple rooms as read simultaneously.
 *
 * @param mx - Matrix client instance
 * @returns A function to mark multiple rooms as read
 */
export function useMarkRoomsAsRead(mx: MatrixClient) {
  const setUnreadAtom = useSetAtom(roomToUnreadAtom);

  return useCallback(
    async (roomIds: string[], privateReceipt: boolean) => {
      // Immediately clear local unread state for all rooms
      roomIds.forEach((roomId) => {
        setUnreadAtom({ type: 'DELETE', roomId });
      });

      // Send read receipts to the server
      await Promise.all(roomIds.map((roomId) => markAsRead(mx, roomId, privateReceipt)));
    },
    [mx, setUnreadAtom]
  );
}
