"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkflowBuilder = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * Workflow Builder Component
 * Enables visual creation and management of AI agent workflows
 */
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const icons_1 = require("@chakra-ui/icons");
const react_query_1 = require("@tanstack/react-query");
const useApi_1 = require("../../hooks/useApi");
const useAuth_1 = require("../../hooks/useAuth");
const ErrorBoundary_1 = require("../common/ErrorBoundary");
const DeleteConfirmationModal_1 = require("../common/DeleteConfirmationModal");
const StatusBadge_1 = require("../common/StatusBadge");
const useWorkflowValidation_1 = require("../../hooks/useWorkflowValidation");
const ValidationSummary_1 = require("./ValidationSummary");
const workflowAudit_1 = require("../../utils/workflowAudit");
const fi_1 = require("react-icons/fi");
const WorkflowBuilder = ({ initialWorkflowId, onSave, onDelete, readOnly = false, }) => {
    const { isAuthenticated, user } = (0, useAuth_1.useAuth)();
    const api = (0, useApi_1.useApi)();
    const toast = (0, react_2.useToast)();
    const queryClient = (0, react_query_1.useQueryClient)();
    const [selectedNode, setSelectedNode] = (0, react_1.useState)(null);
    const [selectedEdge, setSelectedEdge] = (0, react_1.useState)(null);
    const { validate, hasErrors } = (0, useWorkflowValidation_1.useWorkflowValidation)();
    const [validationResult, setValidationResult] = (0, react_1.useState)(null);
    const [selectedNodeId, setSelectedNodeId] = (0, react_1.useState)(null);
    const [showValidationSummary, setShowValidationSummary] = (0, react_1.useState)(false);
    const [showAudit, setShowAudit] = (0, react_1.useState)(false);
    const [isSaving, setIsSaving] = (0, react_1.useState)(false);
    const { isOpen: isDeleteModalOpen, onOpen: onDeleteModalOpen, onClose: onDeleteModalClose, } = (0, react_2.useDisclosure)();
    const bgColor = (0, react_2.useColorModeValue)('white', 'gray.800');
    const borderColor = (0, react_2.useColorModeValue)('gray.200', 'gray.700');
    // Fetch workflow data
    const { data: workflow, isLoading, error } = (0, react_query_1.useQuery)({
        queryKey: ['workflow', initialWorkflowId],
        queryFn: async () => {
            if (!initialWorkflowId)
                return null;
            const response = await api.get(`/api/workflows/${initialWorkflowId}`);
            return response.data;
        },
        enabled: !!initialWorkflowId && isAuthenticated,
    });
    // Save workflow mutation
    const saveMutation = (0, react_query_1.useMutation)({
        mutationFn: async (workflowData) => {
            const endpoint = workflow?.id
                ? `/api/workflows/${workflow.id}`
                : '/api/workflows';
            const method = workflow?.id ? 'put' : 'post';
            const response = await api[method](endpoint, workflowData);
            return response.data;
        },
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ['workflow', data.id] });
            toast({
                title: 'Workflow saved',
                status: 'success',
                duration: 3000,
            });
            onSave?.(data);
        },
        onError: (error) => {
            toast({
                title: 'Failed to save workflow',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
        },
    });
    // Delete workflow mutation
    const deleteMutation = (0, react_query_1.useMutation)({
        mutationFn: async () => {
            if (!workflow?.id)
                throw new Error('No workflow selected');
            await api.delete(`/api/workflows/${workflow.id}`);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['workflows'] });
            toast({
                title: 'Workflow deleted',
                status: 'success',
                duration: 3000,
            });
            onDelete?.(workflow.id);
        },
        onError: (error) => {
            toast({
                title: 'Failed to delete workflow',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
        },
    });
    // Real-time validation
    (0, react_1.useEffect)(() => {
        const result = validate(workflow);
        setValidationResult(result);
    }, [workflow, validate]);
    // Update validation effect to record audit entries
    (0, react_1.useEffect)(() => {
        if (workflow && validationResult) {
            workflowAudit_1.workflowAudit.recordValidation(workflow, validationResult, user?.id || 'anonymous', 'validate', undefined, {
                environment: process.env.NODE_ENV,
                browser: navigator.userAgent,
                userAgent: navigator.userAgent,
            });
        }
    }, [workflow, validationResult, user]);
    // Update save handler to record audit entries
    const handleSave = async () => {
        if (!workflow)
            return;
        if (validationResult && !validationResult.isValid) {
            setShowValidationSummary(true);
            return;
        }
        try {
            setIsSaving(true);
            await onSave(workflow);
            // Record successful save in audit
            workflowAudit_1.workflowAudit.recordValidation(workflow, validationResult, user?.id || 'anonymous', 'update', undefined, {
                environment: process.env.NODE_ENV,
                browser: navigator.userAgent,
                userAgent: navigator.userAgent,
            });
            toast({
                title: 'Workflow saved',
                status: 'success',
                duration: 3000,
                isClosable: true,
            });
        }
        catch (error) {
            toast({
                title: 'Save failed',
                description: error instanceof Error ? error.message : 'Failed to save workflow',
                status: 'error',
                duration: 5000,
                isClosable: true,
            });
        }
        finally {
            setIsSaving(false);
        }
    };
    const handleDelete = (0, react_1.useCallback)(async () => {
        await deleteMutation.mutateAsync();
        onDeleteModalClose();
    }, [deleteMutation, onDeleteModalClose]);
    const handleNodeSelect = (0, react_1.useCallback)((node) => {
        setSelectedNode(node);
        setSelectedEdge(null);
    }, []);
    const handleEdgeSelect = (0, react_1.useCallback)((edge) => {
        setSelectedEdge(edge);
        setSelectedNode(null);
    }, []);
    if (isLoading) {
        return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, textAlign: "center", children: (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Loading workflow..." }) }));
    }
    if (error) {
        return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, textAlign: "center", children: (0, jsx_runtime_1.jsxs)(react_2.Text, { color: "red.500", children: ["Error loading workflow: ", error.message] }) }));
    }
    return ((0, jsx_runtime_1.jsx)(ErrorBoundary_1.ErrorBoundary, { children: (0, jsx_runtime_1.jsxs)(react_2.Box, { bg: bgColor, borderWidth: "1px", borderColor: borderColor, borderRadius: "lg", p: 4, height: "100%", minHeight: "600px", children: [(0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", height: "100%", children: [(0, jsx_runtime_1.jsxs)(react_2.Flex, { justify: "space-between", align: "center", children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 4, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "xl", fontWeight: "bold", children: workflow?.name || 'New Workflow' }), workflow && ((0, jsx_runtime_1.jsx)(StatusBadge_1.StatusBadge, { status: workflow.status, showIcon: true })), validationResult && ((0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: hasErrors(validationResult) ? 'red' : 'green', cursor: "pointer", onClick: () => setShowValidationSummary(!showValidationSummary), children: hasErrors(validationResult) ? 'Invalid' : 'Valid' }))] }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 2, children: [!readOnly && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Save Workflow", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Save workflow", icon: (0, jsx_runtime_1.jsx)(icons_1.EditIcon, {}), onClick: handleSave, isLoading: isSaving, colorScheme: "blue" }) }), workflow && ((0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Delete Workflow", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Delete workflow", icon: (0, jsx_runtime_1.jsx)(icons_1.DeleteIcon, {}), onClick: onDeleteModalOpen, colorScheme: "red", variant: "ghost" }) }))] })), (0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Preview Workflow", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Preview workflow", icon: (0, jsx_runtime_1.jsx)(icons_1.ViewIcon, {}), onClick: () => { }, variant: "ghost" }) }), (0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Show Audit", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Show audit", icon: (0, jsx_runtime_1.jsx)(fi_1.FiBarChart2, {}), onClick: () => setShowAudit(!showAudit), variant: "ghost" }) })] })] }), (0, jsx_runtime_1.jsx)(react_2.Box, { flex: "1", borderWidth: "1px", borderColor: borderColor, borderRadius: "md", p: 4, position: "relative", children: (0, jsx_runtime_1.jsxs)(react_2.Box, { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", textAlign: "center", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { color: "gray.500", children: workflow ? 'Workflow canvas coming soon...' : 'Create a new workflow to get started' }), !workflow && !readOnly && ((0, jsx_runtime_1.jsx)(react_2.Button, { leftIcon: (0, jsx_runtime_1.jsx)(icons_1.AddIcon, {}), mt: 4, onClick: () => { }, children: "Create Workflow" }))] }) })] }), (0, jsx_runtime_1.jsx)(DeleteConfirmationModal_1.DeleteConfirmationModal, { isOpen: isDeleteModalOpen, onClose: onDeleteModalClose, onConfirm: handleDelete, title: "Delete Workflow", message: `Are you sure you want to delete the workflow "${workflow?.name}"? This action cannot be undone.`, isLoading: deleteMutation.isPending }), (0, jsx_runtime_1.jsxs)(react_2.Modal, { isOpen: showValidationSummary, onClose: () => setShowValidationSummary(false), size: "xl", 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: "Validation Summary" }), (0, jsx_runtime_1.jsx)(react_2.ModalCloseButton, {}), (0, jsx_runtime_1.jsx)(react_2.ModalBody, { children: validationResult && ((0, jsx_runtime_1.jsx)(ValidationSummary_1.ValidationSummary, { result: validationResult, onNodeClick: handleNodeSelect, onErrorClick: (error) => {
                                            setSelectedNodeId(error.nodeId);
                                        }, showDetails: true })) }), (0, jsx_runtime_1.jsx)(react_2.ModalFooter, { children: (0, jsx_runtime_1.jsx)(react_2.Button, { onClick: () => setShowValidationSummary(false), children: "Close" }) })] })] })] }) }));
};
exports.WorkflowBuilder = WorkflowBuilder;
exports.default = exports.WorkflowBuilder;
//# sourceMappingURL=WorkflowBuilder.js.map