"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceNotifications = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const fi_1 = require("react-icons/fi");
const useWebSocket_1 = require("../../hooks/useWebSocket");
const ComplianceNotifications = ({ drupalSettings, experienceBuilder, }) => {
    const [notifications, setNotifications] = (0, react_1.useState)([]);
    const [isOpen, setIsOpen] = (0, react_1.useState)(false);
    const [unreadCount, setUnreadCount] = (0, react_1.useState)(0);
    const toast = (0, react_2.useToast)();
    const bgColor = (0, react_2.useColorModeValue)('white', 'gray.800');
    const borderColor = (0, react_2.useColorModeValue)('gray.200', 'gray.700');
    // WebSocket connection for real-time notifications
    const wsUrl = `${drupalSettings.baseUrl.replace('http', 'ws')}/api/notifications/${drupalSettings.userId}`;
    const { lastMessage, sendMessage } = (0, useWebSocket_1.useWebSocket)(wsUrl);
    (0, react_1.useEffect)(() => {
        // Load initial notifications
        fetchNotifications();
        // Set up periodic refresh
        const refreshInterval = setInterval(fetchNotifications, 60000); // Refresh every minute
        return () => clearInterval(refreshInterval);
    }, [drupalSettings.userId]);
    (0, react_1.useEffect)(() => {
        if (lastMessage) {
            const data = JSON.parse(lastMessage.data);
            handleNewNotification(data);
        }
    }, [lastMessage]);
    const fetchNotifications = async () => {
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/notifications`, {
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Accept': 'application/json',
                },
            });
            if (!response.ok)
                throw new Error('Failed to fetch notifications');
            const data = await response.json();
            setNotifications(data.notifications);
            setUnreadCount(data.notifications.filter((n) => !n.read).length);
            // Notify Experience Builder
            experienceBuilder?.onAction?.('notifications_updated', data);
        }
        catch (err) {
            console.error('Error fetching notifications:', err);
        }
    };
    const handleNewNotification = (notification) => {
        // Check notification settings
        if (!drupalSettings.notificationSettings.enableNotifications)
            return;
        if (notification.type === 'alert') {
            if (notification.severity === 'critical' && !drupalSettings.notificationSettings.notifyOnCritical)
                return;
            if (notification.severity === 'high' && !drupalSettings.notificationSettings.notifyOnHigh)
                return;
        }
        if (notification.type === 'score_change' && !drupalSettings.notificationSettings.notifyOnScoreChange)
            return;
        // Add notification to state
        setNotifications(prev => [notification, ...prev]);
        setUnreadCount(prev => prev + 1);
        // Show toast notification
        toast({
            title: notification.title,
            description: notification.message,
            status: getSeverityStatus(notification.severity),
            duration: 5000,
            isClosable: true,
            position: 'top-right',
        });
        // Notify Experience Builder
        experienceBuilder?.onAction?.('notification_received', notification);
    };
    const markAsRead = async (notificationId) => {
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/notifications/${notificationId}/read`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok)
                throw new Error('Failed to mark notification as read');
            setNotifications(prev => prev.map(n => n.id === notificationId ? { ...n, read: true } : n));
            setUnreadCount(prev => Math.max(0, prev - 1));
            // Notify Experience Builder
            experienceBuilder?.onAction?.('notification_read', { notificationId });
        }
        catch (err) {
            console.error('Error marking notification as read:', err);
        }
    };
    const markAllAsRead = async () => {
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/notifications/read-all`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok)
                throw new Error('Failed to mark all notifications as read');
            setNotifications(prev => prev.map(n => ({ ...n, read: true })));
            setUnreadCount(0);
            // Notify Experience Builder
            experienceBuilder?.onAction?.('all_notifications_read', {});
        }
        catch (err) {
            console.error('Error marking all notifications as read:', err);
        }
    };
    const getSeverityStatus = (severity) => {
        switch (severity) {
            case 'critical':
                return 'error';
            case 'high':
                return 'warning';
            case 'medium':
                return 'info';
            case 'low':
                return 'success';
            default:
                return 'info';
        }
    };
    const getSeverityColor = (severity) => {
        switch (severity) {
            case 'critical':
                return 'red';
            case 'high':
                return 'orange';
            case 'medium':
                return 'yellow';
            case 'low':
                return 'blue';
            default:
                return 'gray';
        }
    };
    // If in Experience Builder edit mode, show a simplified view
    if (experienceBuilder?.isEditing) {
        return ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, borderWidth: "2px", borderStyle: "dashed", borderRadius: "lg", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { children: "Compliance Notifications" }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "gray.500", children: "This component will display compliance notifications when placed on a page." })] }));
    }
    return ((0, jsx_runtime_1.jsxs)(react_2.Box, { position: "relative", children: [(0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Compliance notifications", icon: (0, jsx_runtime_1.jsx)(fi_1.FiBell, {}), onClick: () => setIsOpen(true), position: "relative", "data-eb-block-id": experienceBuilder?.blockId, children: unreadCount > 0 && ((0, jsx_runtime_1.jsx)(react_2.Badge, { position: "absolute", top: "-1", right: "-1", colorScheme: "red", borderRadius: "full", minW: "20px", h: "20px", display: "flex", alignItems: "center", justifyContent: "center", children: unreadCount })) }), (0, jsx_runtime_1.jsxs)(react_2.Drawer, { isOpen: isOpen, placement: "right", onClose: () => setIsOpen(false), size: "md", children: [(0, jsx_runtime_1.jsx)(react_2.DrawerOverlay, {}), (0, jsx_runtime_1.jsxs)(react_2.DrawerContent, { children: [(0, jsx_runtime_1.jsx)(react_2.DrawerCloseButton, {}), (0, jsx_runtime_1.jsx)(react_2.DrawerHeader, { borderBottomWidth: "1px", children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { children: "Compliance Notifications" }), unreadCount > 0 && ((0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", leftIcon: (0, jsx_runtime_1.jsx)(fi_1.FiCheck, {}), onClick: markAllAsRead, children: "Mark all as read" }))] }) }), (0, jsx_runtime_1.jsx)(react_2.DrawerBody, { p: 0, children: (0, jsx_runtime_1.jsx)(react_2.VStack, { spacing: 0, align: "stretch", children: notifications.length === 0 ? ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, textAlign: "center", children: (0, jsx_runtime_1.jsx)(react_2.Text, { color: "gray.500", children: "No notifications" }) })) : (notifications.map((notification) => ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, borderBottomWidth: "1px", borderColor: borderColor, bg: notification.read ? bgColor : 'blue.50', children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", mb: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: getSeverityColor(notification.severity), children: notification.severity }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "gray.500", children: new Date(notification.timestamp).toLocaleString() })] }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontWeight: "bold", mb: 1, children: notification.title }), (0, jsx_runtime_1.jsx)(react_2.Text, { mb: 2, children: notification.message }), !notification.read && ((0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", leftIcon: (0, jsx_runtime_1.jsx)(fi_1.FiCheck, {}), onClick: () => markAsRead(notification.id), children: "Mark as read" }))] }, notification.id)))) }) })] })] })] }));
};
exports.ComplianceNotifications = ComplianceNotifications;
//# sourceMappingURL=ComplianceNotifications.js.map