import { useEffect, useCallback } from 'react';
import { useSocketContext, useSocketContextSafe } from '@/contexts/SocketContext';
import { SocketEvents } from '@/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 socketContext = useSocketContextSafe();

    useEffect(() => {
        // If socket context is not available, skip
        if (!socketContext) return;
        
        const { on, off, isConnected } = socketContext;
        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);
        };
    }, [socketContext?.isConnected, userId, onNotification]);

    return { isConnected: socketContext?.isConnected || false };
};
