"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceDashboard = 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 recharts_1 = require("recharts");
const useWebSocket_1 = require("../../hooks/useWebSocket");
const ComplianceDashboard = ({ workflowId, onAlertAction, }) => {
    const [status, setStatus] = (0, react_1.useState)(null);
    const [alerts, setAlerts] = (0, react_1.useState)([]);
    const [metrics, setMetrics] = (0, react_1.useState)([]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(true);
    const [error, setError] = (0, react_1.useState)(null);
    const bgColor = (0, react_2.useColorModeValue)('white', 'gray.800');
    const borderColor = (0, react_2.useColorModeValue)('gray.200', 'gray.700');
    // WebSocket connection for real-time updates
    const { lastMessage, sendMessage } = (0, useWebSocket_1.useWebSocket)(`ws://localhost:8000/api/workflows/${workflowId}/compliance`);
    (0, react_1.useEffect)(() => {
        // Load initial data
        fetchComplianceData();
        // Set up periodic refresh
        const refreshInterval = setInterval(fetchComplianceData, 30000); // Refresh every 30 seconds
        return () => clearInterval(refreshInterval);
    }, [workflowId]);
    (0, react_1.useEffect)(() => {
        if (lastMessage) {
            const data = JSON.parse(lastMessage.data);
            switch (data.type) {
                case 'status_update':
                    setStatus(data.payload);
                    break;
                case 'alert':
                    setAlerts(prev => [data.payload, ...prev].slice(0, 10)); // Keep last 10 alerts
                    break;
                case 'metrics_update':
                    setMetrics(prev => [...prev, data.payload].slice(-30)); // Keep last 30 metrics
                    break;
            }
        }
    }, [lastMessage]);
    const fetchComplianceData = async () => {
        try {
            setIsLoading(true);
            const response = await fetch(`/api/workflows/${workflowId}/compliance`);
            if (!response.ok)
                throw new Error('Failed to fetch compliance data');
            const data = await response.json();
            setStatus(data.status);
            setAlerts(data.alerts);
            setMetrics(data.metrics);
            setError(null);
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'An error occurred');
        }
        finally {
            setIsLoading(false);
        }
    };
    const getSeverityColor = (severity) => {
        switch (severity.toLowerCase()) {
            case 'critical':
                return 'red';
            case 'high':
                return 'orange';
            case 'medium':
                return 'yellow';
            case 'low':
                return 'blue';
            default:
                return 'gray';
        }
    };
    const getStatusColor = (score) => {
        if (score >= 90)
            return 'green';
        if (score >= 70)
            return 'yellow';
        return 'red';
    };
    if (error) {
        return ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: "error", children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: "Error loading compliance data" }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: error })] }));
    }
    return ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, bg: bgColor, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", mb: 6, children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "lg", children: "Compliance Dashboard" }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Refresh compliance data", icon: (0, jsx_runtime_1.jsx)(fi_1.FiRefreshCw, {}), onClick: fetchComplianceData, isLoading: isLoading }), (0, jsx_runtime_1.jsxs)(react_2.Menu, { children: [(0, jsx_runtime_1.jsx)(react_2.MenuButton, { as: react_2.Button, rightIcon: (0, jsx_runtime_1.jsx)(fi_1.FiClock, {}), children: "Time Range" }), (0, jsx_runtime_1.jsxs)(react_2.MenuList, { children: [(0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => sendMessage({ type: 'set_time_range', range: '1h' }), children: "Last Hour" }), (0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => sendMessage({ type: 'set_time_range', range: '24h' }), children: "Last 24 Hours" }), (0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => sendMessage({ type: 'set_time_range', range: '7d' }), children: "Last 7 Days" }), (0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => sendMessage({ type: 'set_time_range', range: '30d' }), children: "Last 30 Days" })] })] })] })] }), (0, jsx_runtime_1.jsxs)(react_2.Grid, { templateColumns: "repeat(3, 1fr)", gap: 6, mb: 8, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Overall Compliance" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { color: getStatusColor(status?.overall_score || 0), children: [status?.overall_score || 0, "%"] }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: status?.trend === 'up' ? 'increase' : 'decrease' }), status?.trend === 'up' ? 'Improving' : 'Needs attention'] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Active Alerts" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { color: alerts.length > 0 ? 'red' : 'green', children: alerts.length }), (0, jsx_runtime_1.jsx)(react_2.StatHelpText, { children: alerts.length > 0 ? 'Requires attention' : 'All clear' })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Resource Usage" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [status?.resource_usage?.current_usage || 0, " / ", status?.resource_usage?.limit || 100] }), (0, jsx_runtime_1.jsx)(react_2.StatHelpText, { children: "API calls this period" })] })] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { mb: 8, h: "300px", children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", mb: 4, children: "Compliance Trend" }), (0, jsx_runtime_1.jsx)(recharts_1.ResponsiveContainer, { width: "100%", height: "100%", children: (0, jsx_runtime_1.jsxs)(recharts_1.LineChart, { data: metrics, children: [(0, jsx_runtime_1.jsx)(recharts_1.CartesianGrid, { strokeDasharray: "3 3" }), (0, jsx_runtime_1.jsx)(recharts_1.XAxis, { dataKey: "timestamp" }), (0, jsx_runtime_1.jsx)(recharts_1.YAxis, { domain: [0, 100] }), (0, jsx_runtime_1.jsx)(recharts_1.Tooltip, {}), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "security", stroke: "#4299E1", name: "Security" }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "data", stroke: "#48BB78", name: "Data" }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "llm", stroke: "#ED8936", name: "LLM" })] }) })] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { mb: 8, children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", mb: 4, children: "Active Alerts" }), alerts.length === 0 ? ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: "success", children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: "No active alerts" }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: "All compliance checks are passing." })] })) : ((0, jsx_runtime_1.jsx)(react_2.VStack, { align: "stretch", spacing: 4, children: alerts.map((alert) => ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: alert.severity === 'critical' ? 'error' : 'warning', variant: "left-accent", children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsxs)(react_2.Box, { flex: "1", children: [(0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: alert.title }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: alert.description })] }), alert.actions && ((0, jsx_runtime_1.jsx)(react_2.HStack, { children: alert.actions.map((action) => ((0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", onClick: () => onAlertAction?.(alert.id, action.id), children: action.label }, action.id))) }))] }, alert.id))) }))] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", mb: 4, children: "Recent Audit Log" }), (0, jsx_runtime_1.jsxs)(react_2.Table, { variant: "simple", children: [(0, jsx_runtime_1.jsx)(react_2.Thead, { children: (0, jsx_runtime_1.jsxs)(react_2.Tr, { children: [(0, jsx_runtime_1.jsx)(react_2.Th, { children: "Time" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Type" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Severity" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Message" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Score" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Tbody, { children: status?.recent_logs?.map((log) => ((0, jsx_runtime_1.jsxs)(react_2.Tr, { children: [(0, jsx_runtime_1.jsx)(react_2.Td, { children: new Date(log.timestamp).toLocaleString() }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: log.type === 'llm' ? 'purple' : 'blue', children: log.type }) }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: getSeverityColor(log.severity), children: log.severity }) }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: log.message }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: (0, jsx_runtime_1.jsx)(react_2.Progress, { value: log.score, colorScheme: getStatusColor(log.score), size: "sm", width: "100px" }) })] }, log.id))) })] })] })] }));
};
exports.ComplianceDashboard = ComplianceDashboard;
//# sourceMappingURL=ComplianceDashboard.js.map