// src/components/DataProvider.tsx
"use client";

import { unreadSystemNotifications } from "@core/app/user/profile/notifications/Notifications.Service";
import { UnreadNotificationResults } from "@core/Models/SystemNotifications.model";
import { getClientSocket } from "@core/Services/Socket.service";
import { useHeaderStore } from "@core/Store/Header.Store";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { useEffect, useState } from "react";
import { Socket } from "socket.io-client";

export function SystemNotificationsProvider() {
    const SessionInfo = useSessionStore();
    const header = useHeaderStore();

    const [clientSocket, setClientSocket] = useState<Socket | undefined>(undefined);

    const checkNotifications = () => {
        unreadSystemNotifications({
            userId: SessionInfo.userId,
            sessionUser: SessionInfo.userId,
        }).then((response) => {
            header.setNotificationsCount(response.count);
        });
    };

    useEffect(() => {
        if (!SessionInfo.loged) {
            header.setNotificationsCount(0);
            if (clientSocket) {
                clientSocket.off("new_system_notification");
            }
            return;
        }
        if (!SessionInfo.userId) {
            return;
        }

        checkNotifications();

        if (clientSocket) {
            return;
        }

        const socket = getClientSocket(SessionInfo.userId);
        setClientSocket(socket);
    }, [SessionInfo.loged]);

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

        clientSocket.on(
            "new_system_notification",
            (unreadNotifications: UnreadNotificationResults) => {
                header.setNotificationsCount(unreadNotifications.count);
            }
        );

        return () => {
            clientSocket.off("new_system_notification");
        };
    }, [clientSocket]);

    return null;
}
