"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncDashboard = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const bfui_1 = require("@bluefly/bfui");
const react_query_1 = require("@tanstack/react-query");
const charts_1 = require("@bluefly/bfui/charts");
const date_fns_1 = require("date-fns");
const useSyncApi_1 = require("../../hooks/useSyncApi");
const SyncDashboard = ({ refreshInterval = 30000, onError, onSyncTriggered, onConflictResolved, }) => {
    const toast = (0, bfui_1.useToast)();
    const syncApi = (0, useSyncApi_1.useSyncApi)();
    const [selectedOperation, setSelectedOperation] = (0, react_1.useState)(null);
    const [selectedConflict, setSelectedConflict] = (0, react_1.useState)(null);
    const [resolutionStrategy, setResolutionStrategy] = (0, react_1.useState)('');
    const [customResolution, setCustomResolution] = (0, react_1.useState)('');
    // Fetch sync statistics
    const { data: stats, error: statsError } = (0, react_query_1.useQuery)({
        queryKey: ['syncStats'],
        queryFn: syncApi.getStats,
        refetchInterval: refreshInterval,
    });
    // Fetch recent operations
    const { data: operations, error: operationsError } = (0, react_query_1.useQuery)({
        queryKey: ['syncOperations'],
        queryFn: syncApi.getOperations,
        refetchInterval: refreshInterval,
    });
    // Fetch conflicts
    const { data: conflicts, error: conflictsError } = (0, react_query_1.useQuery)({
        queryKey: ['syncConflicts'],
        queryFn: syncApi.getConflicts,
        refetchInterval: refreshInterval,
    });
    // Trigger sync mutation
    const triggerSync = (0, react_query_1.useMutation)({
        mutationFn: syncApi.triggerSync,
        onSuccess: (data) => {
            toast.success('Sync operation triggered successfully');
            onSyncTriggered?.(data.configId);
        },
        onError: (error) => {
            toast.error('Failed to trigger sync operation');
            onError?.(error);
        },
    });
    // Resolve conflict mutation
    const resolveConflict = (0, react_query_1.useMutation)({
        mutationFn: syncApi.resolveConflict,
        onSuccess: (data) => {
            toast.success('Conflict resolved successfully');
            setSelectedConflict(null);
            onConflictResolved?.(data.conflictId);
        },
        onError: (error) => {
            toast.error('Failed to resolve conflict');
            onError?.(error);
        },
    });
    // Handle error effects
    (0, react_1.useEffect)(() => {
        if (statsError || operationsError || conflictsError) {
            const error = statsError || operationsError || conflictsError;
            onError?.(error);
        }
    }, [statsError, operationsError, conflictsError, onError]);
    // Prepare chart data
    const statusChartData = {
        labels: ['Completed', 'Running', 'Failed', 'Pending'],
        datasets: [{
                data: [
                    stats?.completed || 0,
                    stats?.running || 0,
                    stats?.failed || 0,
                    stats?.pending || 0,
                ],
                backgroundColor: ['#2E7D32', '#1565C0', '#C62828', '#EF6C00'],
            }],
    };
    const directionChartData = {
        labels: ['Push', 'Pull', 'Bidirectional'],
        datasets: [{
                data: [
                    stats?.pushCount || 0,
                    stats?.pullCount || 0,
                    stats?.bidirectionalCount || 0,
                ],
                backgroundColor: ['#2196F3', '#4CAF50', '#FF9800'],
            }],
    };
    // Render status badge
    const renderStatusBadge = (status) => {
        const variants = {
            completed: 'success',
            running: 'info',
            failed: 'error',
            pending: 'warning',
        };
        return ((0, jsx_runtime_1.jsx)(bfui_1.Badge, { variant: variants[status], children: status.charAt(0).toUpperCase() + status.slice(1) }));
    };
    // Handle conflict resolution
    const handleResolveConflict = (0, react_1.useCallback)(async () => {
        if (!selectedConflict || !resolutionStrategy)
            return;
        await resolveConflict.mutateAsync({
            conflictId: selectedConflict.id,
            strategy: resolutionStrategy,
            customResolution: customResolution || undefined,
        });
    }, [selectedConflict, resolutionStrategy, customResolution, resolveConflict]);
    if (!stats || !operations || !conflicts) {
        return (0, jsx_runtime_1.jsx)(bfui_1.Spinner, { size: "large" });
    }
    return ((0, jsx_runtime_1.jsxs)("div", { className: "sync-dashboard", children: [(0, jsx_runtime_1.jsxs)(bfui_1.Grid, { container: true, spacing: 3, children: [(0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { children: (0, jsx_runtime_1.jsxs)("div", { className: "sync-dashboard__header", children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "h4", children: "Sync Dashboard" }), (0, jsx_runtime_1.jsx)(bfui_1.Button, { variant: "primary", onClick: () => triggerSync.mutate(), loading: triggerSync.isPending, children: "Trigger Sync" })] }) }) }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, md: 6, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { title: "Sync Statistics", children: (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { container: true, spacing: 2, children: [(0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 6, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Total Operations" }), (0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "h3", children: stats.totalOperations })] }), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 6, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Success Rate" }), (0, jsx_runtime_1.jsxs)(bfui_1.Typography, { variant: "h3", children: [stats.successRate, "%"] })] }), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 6, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Active Operations" }), (0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "h3", children: stats.activeOperations })] }), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 6, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Unresolved Conflicts" }), (0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "h3", children: stats.unresolvedConflicts })] })] }) }) }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, md: 6, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { title: "Operation Status", children: (0, jsx_runtime_1.jsx)(charts_1.Chart, { type: "doughnut", data: statusChartData, options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                } }) }) }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, md: 6, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { title: "Sync Direction", children: (0, jsx_runtime_1.jsx)(charts_1.Chart, { type: "pie", data: directionChartData, options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                } }) }) }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { title: "Recent Operations", children: (0, jsx_runtime_1.jsx)(bfui_1.Table, { data: operations, columns: [
                                    {
                                        header: 'ID',
                                        accessor: 'id',
                                        cell: (value) => (0, jsx_runtime_1.jsx)("code", { children: value }),
                                    },
                                    {
                                        header: 'Status',
                                        accessor: 'status',
                                        cell: (value) => renderStatusBadge(value),
                                    },
                                    {
                                        header: 'Direction',
                                        accessor: 'direction',
                                    },
                                    {
                                        header: 'Started',
                                        accessor: 'startedAt',
                                        cell: (value) => (0, date_fns_1.formatDistanceToNow)(new Date(value), { addSuffix: true }),
                                    },
                                    {
                                        header: 'Duration',
                                        accessor: 'duration',
                                        cell: (value) => `${value}s`,
                                    },
                                    {
                                        header: 'Actions',
                                        cell: (row) => ((0, jsx_runtime_1.jsx)(bfui_1.Button, { variant: "secondary", size: "small", onClick: () => setSelectedOperation(row.original), children: "Details" })),
                                    },
                                ] }) }) }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsx)(bfui_1.Card, { title: "Sync Conflicts", children: (0, jsx_runtime_1.jsx)(bfui_1.Table, { data: conflicts, columns: [
                                    {
                                        header: 'ID',
                                        accessor: 'id',
                                        cell: (value) => (0, jsx_runtime_1.jsx)("code", { children: value }),
                                    },
                                    {
                                        header: 'Type',
                                        accessor: 'type',
                                    },
                                    {
                                        header: 'Created',
                                        accessor: 'createdAt',
                                        cell: (value) => (0, date_fns_1.formatDistanceToNow)(new Date(value), { addSuffix: true }),
                                    },
                                    {
                                        header: 'Status',
                                        accessor: 'status',
                                        cell: (value) => renderStatusBadge(value),
                                    },
                                    {
                                        header: 'Actions',
                                        cell: (row) => ((0, jsx_runtime_1.jsx)(bfui_1.Button, { variant: "secondary", size: "small", onClick: () => setSelectedConflict(row.original), children: "Resolve" })),
                                    },
                                ] }) }) })] }), (0, jsx_runtime_1.jsx)(bfui_1.Modal, { open: !!selectedOperation, onClose: () => setSelectedOperation(null), title: "Operation Details", children: selectedOperation && ((0, jsx_runtime_1.jsx)("div", { className: "sync-dashboard__modal-content", children: (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { container: true, spacing: 2, children: [(0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 12, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Overview" }), (0, jsx_runtime_1.jsxs)("dl", { className: "sync-dashboard__details-list", children: [(0, jsx_runtime_1.jsx)("dt", { children: "ID" }), (0, jsx_runtime_1.jsx)("dd", { children: (0, jsx_runtime_1.jsx)("code", { children: selectedOperation.id }) }), (0, jsx_runtime_1.jsx)("dt", { children: "Status" }), (0, jsx_runtime_1.jsx)("dd", { children: renderStatusBadge(selectedOperation.status) }), (0, jsx_runtime_1.jsx)("dt", { children: "Direction" }), (0, jsx_runtime_1.jsx)("dd", { children: selectedOperation.direction }), (0, jsx_runtime_1.jsx)("dt", { children: "Started" }), (0, jsx_runtime_1.jsx)("dd", { children: new Date(selectedOperation.startedAt).toLocaleString() }), (0, jsx_runtime_1.jsx)("dt", { children: "Duration" }), (0, jsx_runtime_1.jsxs)("dd", { children: [selectedOperation.duration, "s"] })] })] }), selectedOperation.error && ((0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsx)(bfui_1.Alert, { variant: "error", title: "Error", children: selectedOperation.error }) })), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 12, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Statistics" }), (0, jsx_runtime_1.jsxs)("dl", { className: "sync-dashboard__stats-list", children: [(0, jsx_runtime_1.jsx)("dt", { children: "Items Processed" }), (0, jsx_runtime_1.jsx)("dd", { children: selectedOperation.stats.itemsProcessed }), (0, jsx_runtime_1.jsx)("dt", { children: "Items Succeeded" }), (0, jsx_runtime_1.jsx)("dd", { children: selectedOperation.stats.itemsSucceeded }), (0, jsx_runtime_1.jsx)("dt", { children: "Items Failed" }), (0, jsx_runtime_1.jsx)("dd", { children: selectedOperation.stats.itemsFailed })] })] })] }) })) }), (0, jsx_runtime_1.jsx)(bfui_1.Modal, { open: !!selectedConflict, onClose: () => setSelectedConflict(null), title: "Resolve Conflict", children: selectedConflict && ((0, jsx_runtime_1.jsx)("div", { className: "sync-dashboard__modal-content", children: (0, jsx_runtime_1.jsx)(bfui_1.Form, { onSubmit: handleResolveConflict, children: (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { container: true, spacing: 2, children: [(0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 12, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Conflict Details" }), (0, jsx_runtime_1.jsxs)("dl", { className: "sync-dashboard__details-list", children: [(0, jsx_runtime_1.jsx)("dt", { children: "ID" }), (0, jsx_runtime_1.jsx)("dd", { children: (0, jsx_runtime_1.jsx)("code", { children: selectedConflict.id }) }), (0, jsx_runtime_1.jsx)("dt", { children: "Type" }), (0, jsx_runtime_1.jsx)("dd", { children: selectedConflict.type }), (0, jsx_runtime_1.jsx)("dt", { children: "Created" }), (0, jsx_runtime_1.jsx)("dd", { children: new Date(selectedConflict.createdAt).toLocaleString() })] })] }), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 12, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Source Data" }), (0, jsx_runtime_1.jsx)("pre", { className: "sync-dashboard__data-view", children: JSON.stringify(selectedConflict.sourceData, null, 2) })] }), (0, jsx_runtime_1.jsxs)(bfui_1.Grid, { item: true, xs: 12, children: [(0, jsx_runtime_1.jsx)(bfui_1.Typography, { variant: "subtitle2", children: "Target Data" }), (0, jsx_runtime_1.jsx)("pre", { className: "sync-dashboard__data-view", children: JSON.stringify(selectedConflict.targetData, null, 2) })] }), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(bfui_1.Form.Group, { children: [(0, jsx_runtime_1.jsx)(bfui_1.Form.Label, { children: "Resolution Strategy" }), (0, jsx_runtime_1.jsx)(bfui_1.Select, { value: resolutionStrategy, onChange: (e) => setResolutionStrategy(e.target.value), options: [
                                                    { value: 'source', label: 'Use Source Data' },
                                                    { value: 'target', label: 'Use Target Data' },
                                                    { value: 'merge', label: 'Merge Data' },
                                                    { value: 'custom', label: 'Custom Resolution' },
                                                ] })] }) }), resolutionStrategy === 'custom' && ((0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)(bfui_1.Form.Group, { children: [(0, jsx_runtime_1.jsx)(bfui_1.Form.Label, { children: "Custom Resolution" }), (0, jsx_runtime_1.jsx)(bfui_1.TextArea, { value: customResolution, onChange: (e) => setCustomResolution(e.target.value), placeholder: "Enter custom resolution data in JSON format", rows: 4 })] }) })), (0, jsx_runtime_1.jsx)(bfui_1.Grid, { item: true, xs: 12, children: (0, jsx_runtime_1.jsxs)("div", { className: "sync-dashboard__form-actions", children: [(0, jsx_runtime_1.jsx)(bfui_1.Button, { type: "submit", variant: "primary", loading: resolveConflict.isPending, children: "Resolve Conflict" }), (0, jsx_runtime_1.jsx)(bfui_1.Button, { type: "button", variant: "secondary", onClick: () => setSelectedConflict(null), children: "Cancel" })] }) })] }) }) })) })] }));
};
exports.SyncDashboard = SyncDashboard;
exports.default = exports.SyncDashboard;
//# sourceMappingURL=SyncDashboard.js.map