import { useState, useEffect, useCallback } from "react";
import axios from "axios";

const useNotifications = () => {
    const [notifications, setNotifications] = useState([]);
    const [loading, setLoading] = useState(false);

    const loadNotifications = useCallback(() => {
        setLoading(true);
        axios.get('/api/notifications/get').then((response) => {
            setNotifications(response.data.notifications);
            setLoading(false);
        });
    }, []);

    useEffect(() => {
        loadNotifications();
    }, [loadNotifications]);

    const addNotification = (name: string, type: string, config: string): Promise<string> | string => {
        if(name.length < 3) {
            return 'Notification name must be at least 3 characters long';
        }

        return axios.post('/api/notifications/add', { name, type, config })
        .then((response) => {
            return response.data.notification;
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    const deleteNotification = (notificationId: number): Promise<string> | string => {
        return axios.delete('/api/notifications/delete', { params: { notificationId } })
        .then(() => {
            return "Notification deleted successfully";
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    }

    return {
        notifications,
        loading,
        addNotification,
        deleteNotification,
        loadNotifications
    };
}

export default useNotifications;