"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncIntelligence = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const react_query_1 = require("@tanstack/react-query");
const recharts_1 = require("recharts");
const date_fns_1 = require("date-fns");
const useSyncApi_1 = require("../../hooks/useSyncApi");
const SyncIntelligence = ({ configId, refreshInterval = 30000, onError, }) => {
    const toast = (0, react_2.useToast)();
    const { isOpen, onOpen, onClose } = (0, react_2.useDisclosure)();
    const [selectedOperation, setSelectedOperation] = (0, react_1.useState)(null);
    const [selectedConflict, setSelectedConflict] = (0, react_1.useState)(null);
    const syncApi = (0, useSyncApi_1.useSyncApi)();
    // Fetch sync intelligence data
    const { data: intelligenceData, error: intelligenceError, refetch: refetchIntelligence } = (0, react_query_1.useQuery)({
        queryKey: ['syncIntelligence', configId],
        queryFn: () => syncApi.getSyncIntelligence(configId),
        refetchInterval: refreshInterval,
    });
    // Fetch sync predictions
    const { data: predictions, error: predictionsError } = (0, react_query_1.useQuery)({
        queryKey: ['syncPredictions', configId],
        queryFn: () => syncApi.getSyncPredictions(configId),
        refetchInterval: refreshInterval,
    });
    // Fetch sync schedule
    const { data: schedule, error: scheduleError } = (0, react_query_1.useQuery)({
        queryKey: ['syncSchedule', configId],
        queryFn: () => syncApi.getSyncSchedule(configId),
        refetchInterval: refreshInterval,
    });
    // Mutations
    const applyHealingStrategy = (0, react_query_1.useMutation)({
        mutationFn: (operationId) => syncApi.applyHealingStrategy(operationId),
        onSuccess: () => {
            toast({
                title: 'Healing strategy applied',
                status: 'success',
                duration: 5000,
            });
            refetchIntelligence();
        },
        onError: (error) => {
            toast({
                title: 'Failed to apply healing strategy',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
            onError?.(error);
        },
    });
    const updateSchedule = (0, react_query_1.useMutation)({
        mutationFn: (newSchedule) => syncApi.updateSyncSchedule(configId, newSchedule),
        onSuccess: () => {
            toast({
                title: 'Sync schedule updated',
                status: 'success',
                duration: 5000,
            });
            refetchIntelligence();
        },
        onError: (error) => {
            toast({
                title: 'Failed to update schedule',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
            onError?.(error);
        },
    });
    // Error handling
    (0, react_1.useEffect)(() => {
        if (intelligenceError || predictionsError || scheduleError) {
            const error = intelligenceError || predictionsError || scheduleError;
            onError?.(error);
        }
    }, [intelligenceError, predictionsError, scheduleError, onError]);
    // Prepare chart data
    const prepareChartData = (0, react_1.useCallback)((data) => {
        return data.map(item => ({
            ...item,
            timestamp: (0, date_fns_1.format)((0, date_fns_1.parseISO)(item.timestamp), 'MMM dd HH:mm'),
        }));
    }, []);
    // Render prediction confidence
    const renderConfidence = (confidence) => {
        const color = confidence >= 80 ? 'green' : confidence >= 60 ? 'yellow' : 'red';
        return ((0, jsx_runtime_1.jsxs)(react_2.Badge, { colorScheme: color, children: [confidence, "% confidence"] }));
    };
    // Render sync schedule
    const renderSchedule = () => {
        if (!schedule)
            return null;
        return ((0, jsx_runtime_1.jsx)(react_2.Stack, { spacing: 4, children: schedule.recommendations.map((rec, index) => ((0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "sm", children: "Recommended Schedule" }), (0, jsx_runtime_1.jsxs)(react_2.Text, { children: ["Time: ", (0, date_fns_1.format)((0, date_fns_1.parseISO)(rec.time), 'HH:mm')] }), (0, jsx_runtime_1.jsxs)(react_2.Text, { children: ["Frequency: ", rec.frequency] }), (0, jsx_runtime_1.jsxs)(react_2.Text, { children: ["Expected Success Rate: ", rec.expected_success_rate, "%"] }), renderConfidence(rec.confidence), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", color: "gray.500", children: ["Based on: ", rec.basis.join(', ')] })] }) }), (0, jsx_runtime_1.jsx)(react_2.CardFooter, { children: (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", colorScheme: "blue", onClick: () => updateSchedule.mutate(rec), children: "Apply Schedule" }) })] }, index))) }));
    };
    // Render predictions
    const renderPredictions = () => {
        if (!predictions)
            return null;
        return ((0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", children: "Conflict Predictions" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (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: "Type" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Probability" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Impact" }), (0, jsx_runtime_1.jsx)(react_2.Th, { children: "Mitigation" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Tbody, { children: predictions.conflicts.map((pred, index) => ((0, jsx_runtime_1.jsxs)(react_2.Tr, { children: [(0, jsx_runtime_1.jsx)(react_2.Td, { children: pred.type }), (0, jsx_runtime_1.jsxs)(react_2.Td, { children: [pred.probability, "%"] }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: pred.impact === 'high' ? 'red' : pred.impact === 'medium' ? 'yellow' : 'green', children: pred.impact }) }), (0, jsx_runtime_1.jsx)(react_2.Td, { children: pred.mitigation })] }, index))) })] }) })] }), (0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", children: "Performance Predictions" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Expected Success Rate" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [predictions.performance.expected_success_rate, "%"] }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: predictions.performance.trend === 'up' ? 'increase' : 'decrease' }), predictions.performance.trend_description] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Expected Duration" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [predictions.performance.expected_duration, "s"] }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: ["Based on ", predictions.performance.sample_size, " recent operations"] })] })] }) })] })] }));
    };
    // Render healing strategies
    const renderHealingStrategies = () => {
        if (!intelligenceData?.healing_strategies)
            return null;
        return ((0, jsx_runtime_1.jsx)(react_2.Stack, { spacing: 4, children: intelligenceData.healing_strategies.map((strategy, index) => ((0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "sm", children: "Healing Strategy" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 2, children: [(0, jsx_runtime_1.jsxs)(react_2.Text, { children: [(0, jsx_runtime_1.jsx)("strong", { children: "Type:" }), " ", strategy.type] }), (0, jsx_runtime_1.jsxs)(react_2.Text, { children: [(0, jsx_runtime_1.jsx)("strong", { children: "Success Rate:" }), " ", strategy.success_rate, "%"] }), (0, jsx_runtime_1.jsx)(react_2.Text, { children: (0, jsx_runtime_1.jsx)("strong", { children: "Actions:" }) }), (0, jsx_runtime_1.jsx)(react_2.Stack, { pl: 4, children: strategy.actions.map((action, actionIndex) => ((0, jsx_runtime_1.jsxs)(react_2.Text, { children: ["\u2022 ", action.description] }, actionIndex))) }), renderConfidence(strategy.confidence)] }) }), (0, jsx_runtime_1.jsx)(react_2.CardFooter, { children: (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", colorScheme: "green", onClick: () => applyHealingStrategy.mutate(strategy.operation_id), children: "Apply Strategy" }) })] }, index))) }));
    };
    // Render patterns
    const renderPatterns = () => {
        if (!intelligenceData?.patterns)
            return null;
        return ((0, jsx_runtime_1.jsx)(react_2.Stack, { spacing: 4, children: (0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", children: "Sync Patterns" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.Tabs, { children: [(0, jsx_runtime_1.jsxs)(react_2.TabList, { children: [(0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Temporal" }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Performance" }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Error" })] }), (0, jsx_runtime_1.jsxs)(react_2.TabPanels, { children: [(0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: (0, jsx_runtime_1.jsx)(recharts_1.ResponsiveContainer, { width: "100%", height: 300, children: (0, jsx_runtime_1.jsxs)(recharts_1.LineChart, { data: prepareChartData(intelligenceData.patterns.temporal), 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, {}), (0, jsx_runtime_1.jsx)(recharts_1.Tooltip, {}), (0, jsx_runtime_1.jsx)(recharts_1.Legend, {}), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "operations", stroke: "#8884d8" }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "success_rate", stroke: "#82ca9d" })] }) }) }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: (0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Average Duration" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData.patterns.performance.average_duration, "s"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Success Rate" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData.patterns.performance.success_rate, "%"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Conflict Rate" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData.patterns.performance.conflict_rate, "%"] })] })] }) }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: (0, jsx_runtime_1.jsx)(react_2.Stack, { spacing: 4, children: Object.entries(intelligenceData.patterns.error).map(([type, data]) => ((0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "sm", mb: 2, children: type }), (0, jsx_runtime_1.jsx)(react_2.Progress, { value: data.percentage, colorScheme: data.percentage > 50 ? 'red' : data.percentage > 20 ? 'yellow' : 'green', mb: 2 }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", color: "gray.500", children: [data.count, " occurrences"] })] }, type))) }) })] })] }) })] }) }));
    };
    return ((0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 6, children: [(0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "lg", children: "Sync Intelligence" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Overall Health" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData?.health_score ?? 0, "%"] }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: intelligenceData?.health_trend === 'up' ? 'increase' : 'decrease' }), intelligenceData?.health_trend_description] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stack, { direction: "row", spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Prediction Accuracy" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData?.prediction_accuracy ?? 0, "%"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Healing Success" }), (0, jsx_runtime_1.jsxs)(react_2.StatNumber, { children: [intelligenceData?.healing_success_rate ?? 0, "%"] })] })] })] }) })] }), (0, jsx_runtime_1.jsxs)(react_2.Tabs, { children: [(0, jsx_runtime_1.jsxs)(react_2.TabList, { children: [(0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Predictions" }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Schedule" }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Healing" }), (0, jsx_runtime_1.jsx)(react_2.Tab, { children: "Patterns" })] }), (0, jsx_runtime_1.jsxs)(react_2.TabPanels, { children: [(0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: renderPredictions() }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: renderSchedule() }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: renderHealingStrategies() }), (0, jsx_runtime_1.jsx)(react_2.TabPanel, { children: renderPatterns() })] })] }), (intelligenceError || predictionsError || scheduleError) && ((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 sync intelligence" }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: (intelligenceError || predictionsError || scheduleError)?.message })] }))] }), (0, jsx_runtime_1.jsxs)(react_2.Modal, { isOpen: isOpen, onClose: onClose, children: [(0, jsx_runtime_1.jsx)(react_2.ModalOverlay, {}), (0, jsx_runtime_1.jsxs)(react_2.ModalContent, { children: [(0, jsx_runtime_1.jsx)(react_2.ModalHeader, { children: "Apply Healing Strategy" }), (0, jsx_runtime_1.jsx)(react_2.ModalCloseButton, {}), (0, jsx_runtime_1.jsx)(react_2.ModalBody, { children: selectedOperation && ((0, jsx_runtime_1.jsxs)(react_2.Stack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Operation ID" }), (0, jsx_runtime_1.jsx)(react_2.Input, { value: selectedOperation.id, isReadOnly: true })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Strategy Type" }), (0, jsx_runtime_1.jsxs)(react_2.Select, { children: [(0, jsx_runtime_1.jsx)("option", { value: "retry", children: "Retry Operation" }), (0, jsx_runtime_1.jsx)("option", { value: "transform", children: "Transform Data" }), (0, jsx_runtime_1.jsx)("option", { value: "validate", children: "Validate Data" }), (0, jsx_runtime_1.jsx)("option", { value: "update_config", children: "Update Configuration" })] })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { children: "Strategy Parameters" }), (0, jsx_runtime_1.jsx)(react_2.Textarea, { placeholder: "Enter strategy parameters in JSON format" })] })] })) }), (0, jsx_runtime_1.jsxs)(react_2.ModalFooter, { children: [(0, jsx_runtime_1.jsx)(react_2.Button, { variant: "ghost", mr: 3, onClick: onClose, children: "Cancel" }), (0, jsx_runtime_1.jsx)(react_2.Button, { colorScheme: "blue", onClick: () => {
                                            if (selectedOperation) {
                                                applyHealingStrategy.mutate(selectedOperation.id);
                                                onClose();
                                            }
                                        }, children: "Apply Strategy" })] })] })] })] }));
};
exports.SyncIntelligence = SyncIntelligence;
//# sourceMappingURL=SyncIntelligence.js.map