'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSignalRContext } from '@/contexts/signalrProvider';
import { fetchApi } from '@/lib/utils/client';
import { NotificationItem, NotePreview } from '@/types/notification';
import { NotificationReadRequest } from '@/types/request/notification/read';

export type { NotificationItem, NotePreview };

export function useNotification()
{
	const { chatConnection } = useSignalRContext();
	const [unreadNotifCount, setUnreadNotifCount] = useState(0);
	const [unreadNoteCount, setUnreadNoteCount] = useState(0);
	const [latestNotification, setLatestNotification] = useState<NotificationItem|null>(null);
	const [latestNote, setLatestNote] = useState<NotePreview|null>(null);

	useEffect(() => {
		if (!chatConnection) {
			return;
		}

		// AppHub에서 알림/쪽지 이벤트 수신
		chatConnection.on('ReceiveNotification', (data: NotificationItem) => {
			setLatestNotification(data);
			setUnreadNotifCount(prev => prev + 1);
		});

		chatConnection.on('ReceiveNote', (data: NotePreview) => {
			setLatestNote(data);
			setUnreadNoteCount(prev => prev + 1);
		});

		chatConnection.on('ReceiveUnreadCounts', (notifCount: number, noteCount: number) => {
			setUnreadNotifCount(notifCount);
			setUnreadNoteCount(noteCount);
		});

		return () => {
			chatConnection.off('ReceiveNotification');
			chatConnection.off('ReceiveNote');
			chatConnection.off('ReceiveUnreadCounts');
		};
	}, [chatConnection]);

	const markNotifRead = useCallback(async (notificationID?: number) => {
		await fetchApi('/api/notification/read', {
			method: 'POST',
			body: { notificationID } as NotificationReadRequest,
			silent: true
		});

		if (notificationID) {
			setUnreadNotifCount(prev => Math.max(0, prev - 1));
		} else {
			setUnreadNotifCount(0);
		}
	}, []);

	const clearLatestNotification = useCallback(() => setLatestNotification(null), []);
	const clearLatestNote = useCallback(() => setLatestNote(null), []);

	return {
		unreadNotifCount,
		unreadNoteCount,
		latestNotification,
		latestNote,
		markNotifRead,
		clearLatestNotification,
		clearLatestNote
	};
}