
document.addEventListener('DOMContentLoaded', function () {
    const createProcessModal = document.getElementById('createProcessModal');
    const modalTitle = createProcessModal.querySelector('.modal-title');
    const form = createProcessModal.querySelector('#createProcessForm');
    const processIdInput = createProcessModal.querySelector('#processId');
    const processNameInput = createProcessModal.querySelector('#processName');
    const definitionJsonTextarea = createProcessModal.querySelector('#definitionJson');
    const eligibilityRulesJsonTextarea = createProcessModal.querySelector('#eligibilityRulesJson');

    let definition = {};

    function render() {
        const statusesList = document.getElementById('statuses-list');
        const transitionsList = document.getElementById('transitions-list');
        const initialStatusSelect = document.getElementById('initialStatus');
        const fromStatusSelect = document.getElementById('fromStatusSelect');
        const toStatusSelect = document.getElementById('toStatusSelect');

        statusesList.innerHTML = '';
        transitionsList.innerHTML = '';
        initialStatusSelect.innerHTML = '';
        fromStatusSelect.innerHTML = '';
        toStatusSelect.innerHTML = '';

        if (definition.nodes) {
            for (const nodeId in definition.nodes) {
                const node = definition.nodes[nodeId];
                const statusItem = document.createElement('div');
                statusItem.textContent = node.name;
                statusesList.appendChild(statusItem);

                const option = document.createElement('option');
                option.value = node.id;
                option.textContent = node.name;
                initialStatusSelect.appendChild(option.cloneNode(true));
                fromStatusSelect.appendChild(option.cloneNode(true));
                toStatusSelect.appendChild(option.cloneNode(true));
            }
        }

        if (definition.start_node_id) {
            initialStatusSelect.value = definition.start_node_id;
        }

        if (definition.transitions) {
            definition.transitions.forEach(transition => {
                const transitionItem = document.createElement('div');
                const fromNode = definition.nodes[transition.from] ? definition.nodes[transition.from].name : 'N/A';
                const toNode = definition.nodes[transition.to] ? definition.nodes[transition.to].name : 'N/A';
                let actions = '';
                if(transition.actions) {
                    actions = ' - Actions: ' + JSON.stringify(transition.actions);
                }
                transitionItem.textContent = `${transition.name}: ${fromNode} => ${toNode}${actions}`;
                transitionsList.appendChild(transitionItem);
            });
        }
        
        if (definition.eligibility_rules) {
            eligibilityRulesJsonTextarea.value = JSON.stringify(definition.eligibility_rules, null, 2);
        }
    }

    document.getElementById('addStatusBtn').addEventListener('click', function () {
        const newStatusInput = document.getElementById('newStatusInput');
        const newStatusName = newStatusInput.value.trim();
        if (newStatusName) {
            const newNodeId = (Object.keys(definition.nodes || {}).length + 1).toString();
            if (!definition.nodes) {
                definition.nodes = {};
            }
            definition.nodes[newNodeId] = { id: newNodeId, name: newStatusName };
            newStatusInput.value = '';
            render();
        }
    });

    document.getElementById('addTransitionBtn').addEventListener('click', function () {
        const fromStatus = document.getElementById('fromStatusSelect').value;
        const toStatus = document.getElementById('toStatusSelect').value;
        const transitionActionJson = document.getElementById('transitionActionJson').value;

        if (fromStatus && toStatus) {
            if (!definition.transitions) {
                definition.transitions = [];
            }
            const newTransition = {
                name: `Transition ${definition.transitions.length + 1}`,
                from: fromStatus,
                to: toStatus,
            };
            
            if(transitionActionJson) {
                try {
                    newTransition.actions = JSON.parse(transitionActionJson);
                } catch(e) {
                    alert('Invalid JSON in transition actions');
                    return;
                }
            }

            definition.transitions.push(newTransition);
            document.getElementById('transitionActionJson').value = '';
            render();
        }
    });

    form.addEventListener('submit', function (event) {
        definition.start_node_id = document.getElementById('initialStatus').value;
        
        try {
            const eligibilityRules = eligibilityRulesJsonTextarea.value;
            if(eligibilityRules) {
                definition.eligibility_rules = JSON.parse(eligibilityRules);
            } else {
                delete definition.eligibility_rules;
            }
        } catch(e) {
            alert('Invalid JSON in eligibility rules');
            event.preventDefault();
            return;
        }

        definitionJsonTextarea.value = JSON.stringify(definition, null, 2);
    });

    createProcessModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const isEdit = button.classList.contains('edit-process-btn');

        if (isEdit) {
            const processId = button.dataset.processId;
            const processName = button.dataset.processName;
            const processDefinition = button.dataset.processDefinition;

            modalTitle.textContent = 'Edit Process';
            processIdInput.value = processId;
            processNameInput.value = processName;
            
            try {
                definition = JSON.parse(processDefinition || '{}');
            } catch(e) {
                definition = {};
            }

        } else {
            modalTitle.textContent = 'Create Process';
            processIdInput.value = '';
            processNameInput.value = '';
            definition = {};
        }
        
        eligibilityRulesJsonTextarea.value = '';
        render();
    });
});
