import { useEffect, useCallback } from 'react';
import { useSocketContext } from '@admin/contexts/SocketContext';
import { SocketEvents } from '@admin/types/socket';

/**
 * Custom hook to use socket functionality
 */
export const useSocket = () => {
    const context = useSocketContext();
    return context;
};

/**
 * Hook to listen to a specific socket event
 * @param event - Event name to listen to
 * @param callback - Callback function to handle the event
 * @param dependencies - Optional dependency array
 */
export const useSocketEvent = <T = any>(
    event: string | SocketEvents,
    callback: (data: T) => void,
    dependencies: any[] = []
) => {
    const { on, off } = useSocketContext();

    useEffect(() => {
        on(event, callback);

        return () => {
            off(event, callback);
        };
    }, [event, ...dependencies]);
};

/**
 * Hook to emit socket events easily
 */
export const useSocketEmit = () => {
    const { emit, isConnected } = useSocketContext();

    const emitEvent = useCallback(
        <T = any>(event: string, data: T) => {
            if (!isConnected) {
                console.warn('[useSocketEmit] Cannot emit - socket not connected');
                return false;
            }
            emit(event, data);
            return true;
        },
        [emit, isConnected]
    );

    return { emit: emitEvent, isConnected };
};

/**
 * Hook to handle notifications from socket
 */
export const useSocketNotifications = (
    onNotification: (data: any) => void,
    userId?: string | number
) => {
    const { on, off, isConnected } = useSocketContext();

    useEffect(() => {
        if (!isConnected || !userId) return;

        const handleNotification = (data: any) => {
            // Filter notifications for current user
            if (String(data.userId) === String(userId)) {
                onNotification(data);
            }
        };

        on(SocketEvents.EMIT_NOTIFICATION, handleNotification);

        return () => {
            off(SocketEvents.EMIT_NOTIFICATION, handleNotification);
        };
    }, [isConnected, userId, onNotification]);

    return { isConnected };
};
