"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceReportGenerator = 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 date_fns_1 = require("date-fns");
const COLORS = ['#E53E3E', '#DD6B20', '#ECC94B', '#48BB78'];
const ComplianceReportGenerator = ({ drupalSettings, experienceBuilder, }) => {
    const [settings, setSettings] = (0, react_1.useState)(drupalSettings.defaultReportSettings);
    const [data, setData] = (0, react_1.useState)(null);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [error, setError] = (0, react_1.useState)(null);
    const [isGenerating, setIsGenerating] = (0, react_1.useState)(false);
    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');
    const fetchReportData = (0, react_1.useCallback)(async () => {
        setIsLoading(true);
        setError(null);
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/compliance/reports/generate`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ settings }),
            });
            if (!response.ok)
                throw new Error('Failed to generate report');
            const reportData = await response.json();
            setData(reportData);
            setError(null);
            // Notify Experience Builder
            experienceBuilder?.onAction?.('report_generated', reportData);
        }
        catch (err) {
            console.error('Error generating report:', err);
            setError('Failed to generate compliance report');
            toast({
                title: 'Error',
                description: 'Failed to generate compliance report. Please try again.',
                status: 'error',
                duration: 5000,
                isClosable: true,
            });
        }
        finally {
            setIsLoading(false);
        }
    }, [settings, drupalSettings, toast, experienceBuilder]);
    (0, react_1.useEffect)(() => {
        fetchReportData();
    }, [fetchReportData]);
    const handleSettingChange = (category, setting, value) => {
        setSettings(prev => ({
            ...prev,
            [category]: value,
        }));
    };
    const handleFilterChange = (filterType, value) => {
        setSettings(prev => ({
            ...prev,
            filters: {
                ...prev.filters,
                [filterType]: value,
            },
        }));
    };
    const handleTimeRangeChange = (range) => {
        const now = new Date();
        let startDate;
        switch (range) {
            case 'day':
                startDate = (0, date_fns_1.format)((0, date_fns_1.subDays)(now, 1), 'yyyy-MM-dd');
                break;
            case 'week':
                startDate = (0, date_fns_1.format)((0, date_fns_1.subDays)(now, 7), 'yyyy-MM-dd');
                break;
            case 'month':
                startDate = (0, date_fns_1.format)((0, date_fns_1.subMonths)(now, 1), 'yyyy-MM-dd');
                break;
            case 'quarter':
                startDate = (0, date_fns_1.format)((0, date_fns_1.subMonths)(now, 3), 'yyyy-MM-dd');
                break;
            case 'year':
                startDate = (0, date_fns_1.format)((0, date_fns_1.subYears)(now, 1), 'yyyy-MM-dd');
                break;
            case 'custom':
                startDate = undefined;
                break;
        }
        setSettings(prev => ({
            ...prev,
            timeRange: range,
            startDate,
            endDate: (0, date_fns_1.format)(now, 'yyyy-MM-dd'),
        }));
    };
    const downloadReport = async (format) => {
        setIsGenerating(true);
        setError(null);
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/compliance/reports/download`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ...settings,
                    format,
                }),
            });
            if (!response.ok)
                throw new Error('Failed to download report');
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `compliance-report-${format(new Date(), 'yyyy-MM-dd')}.${format}`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            toast({
                title: 'Report downloaded',
                description: `Your compliance report has been downloaded in ${format.toUpperCase()} format.`,
                status: 'success',
                duration: 5000,
                isClosable: true,
            });
            // Notify Experience Builder
            experienceBuilder?.onAction?.('report_downloaded', { format });
        }
        catch (err) {
            console.error('Error downloading report:', err);
            setError('Failed to download report');
            toast({
                title: 'Error',
                description: 'Failed to download report. Please try again.',
                status: 'error',
                duration: 5000,
                isClosable: true,
            });
        }
        finally {
            setIsGenerating(false);
        }
    };
    const shareReport = async () => {
        try {
            const response = await fetch(`${drupalSettings.baseUrl}/api/compliance/reports/share`, {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': drupalSettings.csrfToken,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(settings),
            });
            if (!response.ok)
                throw new Error('Failed to share report');
            const { shareUrl } = await response.json();
            // Copy to clipboard
            await navigator.clipboard.writeText(shareUrl);
            toast({
                title: 'Report shared',
                description: 'The report link has been copied to your clipboard.',
                status: 'success',
                duration: 5000,
                isClosable: true,
            });
            // Notify Experience Builder
            experienceBuilder?.onAction?.('report_shared', { shareUrl });
        }
        catch (err) {
            console.error('Error sharing report:', err);
            toast({
                title: 'Error',
                description: 'Failed to share report. Please try again.',
                status: 'error',
                duration: 5000,
                isClosable: true,
            });
        }
    };
    // 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 Report Generator" }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "gray.500", children: "This component will generate and display compliance reports when placed on a page." })] }));
    }
    return ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 6, bg: bgColor, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, "data-eb-block-id": experienceBuilder?.blockId, children: [error && ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: "error", mb: 4, children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: "Error" }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: error })] })), (0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", mb: 6, children: [(0, jsx_runtime_1.jsxs)(react_2.VStack, { align: "start", spacing: 1, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "2xl", fontWeight: "bold", children: "Compliance Report" }), (0, jsx_runtime_1.jsx)(react_2.Text, { color: "gray.500", children: "Generate and view detailed compliance reports" })] }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Refresh Report", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Refresh report", icon: (0, jsx_runtime_1.jsx)(fi_1.FiRefreshCw, {}), onClick: fetchReportData, isLoading: isLoading }) }), (0, jsx_runtime_1.jsxs)(react_2.Menu, { children: [(0, jsx_runtime_1.jsx)(react_2.MenuButton, { as: react_2.Button, leftIcon: (0, jsx_runtime_1.jsx)(fi_1.FiDownload, {}), isLoading: isGenerating, children: "Download" }), (0, jsx_runtime_1.jsxs)(react_2.MenuList, { children: [(0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => downloadReport('pdf'), children: "PDF" }), (0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => downloadReport('csv'), children: "CSV" }), (0, jsx_runtime_1.jsx)(react_2.MenuItem, { onClick: () => downloadReport('json'), children: "JSON" })] })] }), (0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Share Report", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Share report", icon: (0, jsx_runtime_1.jsx)(fi_1.FiShare2, {}), onClick: shareReport }) })] })] }), (0, jsx_runtime_1.jsxs)(react_2.Tabs, { variant: "enclosed", colorScheme: "blue", children: [(0, jsx_runtime_1.jsxs)(react_2.TabList, { children: [(0, jsx_runtime_1.jsx)(react_2.Tab, { children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(fi_1.FiBarChart2, {}), (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Summary" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(fi_1.FiTrendingUp, {}), (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Trends" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(fi_1.FiAlertCircle, {}), (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Details" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(fi_1.FiSettings, {}), (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Settings" })] }) })] }), (0, jsx_runtime_1.jsxs)(react_2.TabPanels, { children: [(0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: isLoading ? ((0, jsx_runtime_1.jsxs)(react_2.Box, { textAlign: "center", py: 8, children: [(0, jsx_runtime_1.jsx)(react_2.Spinner, { size: "xl" }), (0, jsx_runtime_1.jsx)(react_2.Text, { mt: 4, children: "Generating report..." })] })) : data ? ((0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 6, align: "stretch", children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Box, { flex: 1, p: 4, bg: "blue.50", borderRadius: "md", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "blue.600", children: "Compliance Score" }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "3xl", fontWeight: "bold", children: [data.summary.complianceScore, "%"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { flex: 1, p: 4, bg: "green.50", borderRadius: "md", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "green.600", children: "Compliant Controls" }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "3xl", fontWeight: "bold", children: data.summary.compliantControls })] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { flex: 1, p: 4, bg: "red.50", borderRadius: "md", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", color: "red.600", children: "Non-Compliant Controls" }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "3xl", fontWeight: "bold", children: data.summary.nonCompliantControls })] })] }), (0, jsx_runtime_1.jsx)(react_2.Box, { h: "300px", children: (0, jsx_runtime_1.jsx)(recharts_1.ResponsiveContainer, { width: "100%", height: "100%", children: (0, jsx_runtime_1.jsxs)(recharts_1.PieChart, { children: [(0, jsx_runtime_1.jsx)(recharts_1.Pie, { data: Object.entries(data.summary.severityDistribution).map(([severity, count]) => ({
                                                                name: severity,
                                                                value: count,
                                                            })), cx: "50%", cy: "50%", labelLine: false, label: ({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`, outerRadius: 80, fill: "#8884d8", dataKey: "value", children: Object.entries(data.summary.severityDistribution).map((entry, index) => ((0, jsx_runtime_1.jsx)(recharts_1.Cell, { fill: COLORS[index % COLORS.length] }, `cell-${index}`))) }), (0, jsx_runtime_1.jsx)(recharts_1.Tooltip, {}), (0, jsx_runtime_1.jsx)(recharts_1.Legend, {})] }) }) })] })) : null }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: isLoading ? ((0, jsx_runtime_1.jsxs)(react_2.Box, { textAlign: "center", py: 8, children: [(0, jsx_runtime_1.jsx)(react_2.Spinner, { size: "xl" }), (0, jsx_runtime_1.jsx)(react_2.Text, { mt: 4, children: "Loading trends..." })] })) : data?.trends ? ((0, jsx_runtime_1.jsx)(react_2.VStack, { spacing: 6, align: "stretch", children: (0, jsx_runtime_1.jsx)(react_2.Box, { h: "400px", children: (0, jsx_runtime_1.jsx)(recharts_1.ResponsiveContainer, { width: "100%", height: "100%", children: (0, jsx_runtime_1.jsxs)(recharts_1.LineChart, { data: data.trends.dates.map((date, index) => ({
                                                    date,
                                                    score: data.trends.scores[index],
                                                    compliant: data.trends.compliantCounts[index],
                                                    nonCompliant: data.trends.nonCompliantCounts[index],
                                                })), margin: {
                                                    top: 5,
                                                    right: 30,
                                                    left: 20,
                                                    bottom: 5,
                                                }, children: [(0, jsx_runtime_1.jsx)(recharts_1.CartesianGrid, { strokeDasharray: "3 3" }), (0, jsx_runtime_1.jsx)(recharts_1.XAxis, { dataKey: "date", tickFormatter: (date) => (0, date_fns_1.format)(new Date(date), 'MMM d') }), (0, jsx_runtime_1.jsx)(recharts_1.YAxis, { yAxisId: "left" }), (0, jsx_runtime_1.jsx)(recharts_1.YAxis, { yAxisId: "right", orientation: "right" }), (0, jsx_runtime_1.jsx)(recharts_1.Tooltip, { labelFormatter: (date) => (0, date_fns_1.format)(new Date(date), 'MMM d, yyyy') }), (0, jsx_runtime_1.jsx)(recharts_1.Legend, {}), (0, jsx_runtime_1.jsx)(recharts_1.Line, { yAxisId: "left", type: "monotone", dataKey: "score", name: "Compliance Score", stroke: "#3182CE", activeDot: { r: 8 } }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { yAxisId: "right", type: "monotone", dataKey: "compliant", name: "Compliant Controls", stroke: "#38A169" }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { yAxisId: "right", type: "monotone", dataKey: "nonCompliant", name: "Non-Compliant Controls", stroke: "#E53E3E" })] }) }) }) })) : null }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: isLoading ? ((0, jsx_runtime_1.jsxs)(react_2.Box, { textAlign: "center", py: 8, children: [(0, jsx_runtime_1.jsx)(react_2.Spinner, { size: "xl" }), (0, jsx_runtime_1.jsx)(react_2.Text, { mt: 4, children: "Loading details..." })] })) : data?.details ? ((0, jsx_runtime_1.jsx)(react_2.VStack, { spacing: 4, align: "stretch", children: data.details.map((item) => ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, borderWidth: "1px", borderColor: borderColor, borderRadius: "md", children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", mb: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontWeight: "bold", children: item.name }), (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: item.status === 'compliant' ? 'green' : 'red', children: item.status })] }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 4, mb: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: "blue", children: item.category }), (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: item.severity === 'critical'
                                                            ? 'red'
                                                            : item.severity === 'high'
                                                                ? 'orange'
                                                                : item.severity === 'medium'
                                                                    ? 'yellow'
                                                                    : 'blue', children: item.severity }), (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: "purple", children: item.region })] }), (0, jsx_runtime_1.jsx)(react_2.Text, { mb: 2, children: item.description }), item.recommendations.length > 0 && ((0, jsx_runtime_1.jsxs)(react_2.Box, { mt: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontWeight: "bold", mb: 1, children: "Recommendations:" }), (0, jsx_runtime_1.jsx)(react_2.VStack, { align: "start", spacing: 1, children: item.recommendations.map((rec, index) => ((0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", children: ["\u2022 ", rec] }, index))) })] }))] }, item.id))) })) : null }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", children: [(0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Time Range" }), (0, jsx_runtime_1.jsxs)(react_2.Select, { value: settings.timeRange, onChange: (e) => handleTimeRangeChange(e.target.value), children: [(0, jsx_runtime_1.jsx)("option", { value: "day", children: "Last 24 Hours" }), (0, jsx_runtime_1.jsx)("option", { value: "week", children: "Last 7 Days" }), (0, jsx_runtime_1.jsx)("option", { value: "month", children: "Last 30 Days" }), (0, jsx_runtime_1.jsx)("option", { value: "quarter", children: "Last 90 Days" }), (0, jsx_runtime_1.jsx)("option", { value: "year", children: "Last 365 Days" }), (0, jsx_runtime_1.jsx)("option", { value: "custom", children: "Custom Range" })] })] }), settings.timeRange === 'custom' && ((0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Start Date" }), (0, jsx_runtime_1.jsx)("input", { type: "date", value: settings.startDate, onChange: (e) => handleSettingChange('startDate', 'startDate', e.target.value) })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "End Date" }), (0, jsx_runtime_1.jsx)("input", { type: "date", value: settings.endDate, onChange: (e) => handleSettingChange('endDate', 'endDate', e.target.value) })] })] })), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Group By" }), (0, jsx_runtime_1.jsxs)(react_2.Select, { value: settings.groupBy, onChange: (e) => handleSettingChange('groupBy', 'groupBy', e.target.value), children: [(0, jsx_runtime_1.jsx)("option", { value: "none", children: "No Grouping" }), (0, jsx_runtime_1.jsx)("option", { value: "severity", children: "Severity" }), (0, jsx_runtime_1.jsx)("option", { value: "category", children: "Category" }), (0, jsx_runtime_1.jsx)("option", { value: "region", children: "Region" })] })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { mb: "0", children: "Include Trends" }), (0, jsx_runtime_1.jsx)(react_2.Switch, { isChecked: settings.includeTrends, onChange: (e) => handleSettingChange('includeTrends', 'includeTrends', e.target.checked) })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { mb: "0", children: "Include Recommendations" }), (0, jsx_runtime_1.jsx)(react_2.Switch, { isChecked: settings.includeRecommendations, onChange: (e) => handleSettingChange('includeRecommendations', 'includeRecommendations', e.target.checked) })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { mb: "0", children: "Include Details" }), (0, jsx_runtime_1.jsx)(react_2.Switch, { isChecked: settings.includeDetails, onChange: (e) => handleSettingChange('includeDetails', 'includeDetails', e.target.checked) })] })] }) })] })] })] }));
};
exports.ComplianceReportGenerator = ComplianceReportGenerator;
//# sourceMappingURL=ComplianceReportGenerator.js.map