{% extends 'base.html' %}

{% block content %}
<div class="router-container">
    <div class="router-header">
        <div class="breadcrumb-nav">
            <a href="{{ url_for('conssheets.admin_processes') }}">Consumption Sheets</a>
            <span class="sep">/</span>
            <a href="{{ url_for('conssheets.process_detail', process_id=process['id']) }}">{{ process['process_name'] }}</a>
            <span class="sep">/</span>
            <a href="{{ url_for('conssheets.process_router', process_id=process['id']) }}">Routing Rules</a>
            <span class="sep">/</span>
            <span class="current">Edit Rule {{ rule['line_number'] }}</span>
        </div>
        <h1 class="page-title">Rule Configuration</h1>
    </div>

    <form action="{{ url_for('conssheets.edit_router_rule', process_id=process['id'], rule_id=rule['id']) }}" method="POST">
        
        <input type="hidden" name="actions_json" id="actionsJson" value="{{ rule['actions_json'] or '[]' }}">

        <div class="logic-grid">
            <div class="logic-panel trigger-panel">
                <div class="panel-header header-trigger">
                    <i class="fas fa-bolt"></i>
                    <h3>Trigger (IF)</h3>
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <label>Line Number</label>
                        <input type="number" class="dark-input" name="line_number" value="{{ rule['line_number'] }}" required>
                        <small>Execution order (e.g. 10)</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Rule Name</label>
                        <input type="text" class="dark-input" name="rule_name" value="{{ rule['rule_name'] }}" required>
                    </div>

                    <div class="form-group">
                        <label>Match Pattern (Regex)</label>
                        <div class="input-icon-wrapper">
                            <i class="fas fa-code"></i>
                            <input type="text" class="dark-input mono-font" name="match_pattern" value="{{ rule['match_pattern'] }}" required>
                        </div>
                        <small class="code-help">
                            <code>.*</code> = Match All<br>
                            <code>^\d{8}-.*</code> = Starts with 8 digits
                        </small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary full-width-btn">Save Rule & Pipeline</button>
                </div>
            </div>

            <div class="logic-panel pipeline-panel">
                <div class="panel-header header-pipeline">
                    <div class="header-left">
                        <i class="fas fa-list-ol"></i>
                        <h3>Action Pipeline (THEN)</h3>
                    </div>
                    <button type="button" class="btn btn-sm btn-success" id="addActionBtn" onclick="openAddModal()">
                        <i class="fas fa-plus"></i> Add Action
                    </button>
                </div>
                <div class="panel-body pipeline-body">
                    
                    <div class="pipeline-node start-node">
                        <span class="badge-pill"><i class="fas fa-barcode"></i> SCAN INPUT</span>
                        <div class="connector-line"></div>
                    </div>

                    <div id="pipelineContainer" class="action-list">
                        </div>

                    <div class="pipeline-node end-node">
                        <div class="connector-line"></div>
                        <span class="badge-pill end-pill">END RULE</span>
                    </div>

                </div>
            </div>
        </div>
    </form>
</div>

<style>
    .router-container { padding: 20px; max-width: 1400px; margin: 0 auto; }
    .logic-grid { display: grid; grid-template-columns: 350px 1fr; gap: 25px; align-items: start; }
    @media (max-width: 900px) { .logic-grid { grid-template-columns: 1fr; } }
    .breadcrumb-nav { margin-bottom: 10px; color: #888; font-size: 0.9rem; }
    .breadcrumb-nav a { color: #aaa; text-decoration: none; }
    .breadcrumb-nav .sep { margin: 0 5px; }
    .breadcrumb-nav .current { color: #fff; }
    .page-title { color: #fff; margin-bottom: 25px; }
    .logic-panel { background: #1a1a1a; border: 1px solid #333; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.3); }
    .panel-header { padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #333; }
    .panel-header h3 { margin: 0; font-size: 1.1rem; color: #fff; margin-left: 10px; }
    .header-trigger { background: #2c3e50; border-bottom-color: #34495e; }
    .header-pipeline { background: #252525; }
    .header-left { display: flex; align-items: center; }
    .panel-body { padding: 20px; }
    .form-group { margin-bottom: 20px; }
    .form-group label { display: block; color: #ccc; margin-bottom: 8px; font-weight: bold; }
    .form-group small { display: block; color: #666; font-size: 0.8rem; margin-top: 5px; }
    .dark-input { width: 100%; padding: 10px; background: #000; border: 1px solid #444; color: #fff; border-radius: 4px; box-sizing: border-box; }
    .dark-input:focus { border-color: #3498db; outline: none; }
    .mono-font { font-family: monospace; letter-spacing: 1px; }
    .code-help code { background: #333; padding: 2px 5px; border-radius: 3px; color: #e74c3c; }
    .full-width-btn { width: 100%; }
    .pipeline-body { display: flex; flex-direction: column; align-items: center; min-height: 400px; background: #121212; }
    .pipeline-node { text-align: center; width: 100%; }
    .badge-pill { background: #333; color: #fff; padding: 8px 16px; border-radius: 20px; border: 1px solid #444; font-weight: bold; display: inline-block; z-index: 2; position: relative; }
    .end-pill { background: #1a1a1a; color: #666; border-style: dashed; }
    .connector-line { height: 20px; width: 2px; background: #333; margin: 0 auto; }
    .action-list { width: 100%; display: flex; flex-direction: column; align-items: center; flex-grow: 1; }
    .input-icon-wrapper { position: relative; }
    .input-icon-wrapper i { position: absolute; left: 10px; top: 12px; color: #666; }
    .input-icon-wrapper input { padding-left: 35px; }
</style>

<div class="modal fade" id="actionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Add Pipeline Action</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="actionForm">
                    <div class="mb-3">
                        <label class="form-label font-weight-bold">Action Type</label>
                        <select class="form-control" id="actionType" onchange="toggleActionFields()">
                            <option value="map">Map Substring (Extract Data)</option>
                            <option value="clean">Clean Data (Trim, Remove Spaces)</option>
                            <option value="duplicate">Check for Duplicates</option>
                            <option value="input">User Input (Open Details Form)</option>
                            <option value="save">Save Record (Commit)</option>
                        </select>
                    </div>

                    <div id="params-map" class="action-params">
                        <div class="row">
                            <div class="col-6">
                                <label>Start Char</label>
                                <input type="number" class="form-control" id="rule_map_start" value="1">
                            </div>
                            <div class="col-6">
                                <label>End Char</label>
                                <input type="number" class="form-control" id="rule_map_end" value="25">
                            </div>
                        </div>
                        <small class="text-muted">Positions are 1-based (1 is the first character)</small>
                    </div>

                    <div id="params-clean" class="action-params" style="display:none;">
                        <label>Cleaning Function</label>
                        <select class="form-control" id="cleanFunc">
                            <option value="TRIM">TRIM (Remove outer spaces)</option>
                            <option value="REMOVE_SPACES">REMOVE_ALL_SPACES</option>
                            <option value="REMOVE_LEADING_ZEROS">REMOVE_LEADING_ZEROS</option>
                            <option value="UPPERCASE">TO_UPPERCASE</option>
                        </select>
                    </div>

                    <div id="params-target" class="mt-3">
                        <label class="font-weight-bold">Target Field</label>
                        <select class="form-control" id="targetField">
                            <option value="">-- Select Field --</option>
                            {% for field in fields %}
                                <option value="{{ field.field_name }}">{{ field.field_label }} ({{ field.field_name }})</option>
                            {% endfor %}
                        </select>
                    </div>

                    <div id="params-duplicate" class="action-params" style="display:none;">
                         <div class="alert alert-info small mb-2">
                            Checks if the value in <strong>Target Field</strong> already exists.
                        </div>
                        <label class="font-weight-bold">Duplicate Behavior</label>
                        <select class="form-control" id="dupBehavior">
                            <option value="WARN">Warn & Ask (Allow Override)</option>
                            <option value="BLOCK">Strict Block (No Duplicates)</option>
                            <option value="SILENT">Silent (Log & Continue)</option>
                        </select>
                    </div>
                     <div id="params-save" class="action-params" style="display:none;">
                        <div class="alert alert-success small">
                            <i class="fas fa-save"></i> <strong>Commit:</strong> If flow reaches here, data will be saved to the database.
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" id="btnSaveAction" class="btn btn-primary" onclick="saveAction()">Add to Pipeline</button>
            </div>
        </div>
    </div>
</div>

<script>
    // --- 1. DATA LOADING ---
    // We safely parse the JSON. If it fails, we start empty to prevent crashes.
    let actions = [];
    try {
        const rawData = document.getElementById('actionsJson').value;
        actions = JSON.parse(rawData || '[]');
    } catch (e) {
        console.error("Pipeline Data Error:", e);
        actions = [];
    }

    let editingIndex = -1; 

    // --- 2. SETUP ---
    document.addEventListener('DOMContentLoaded', function() {
        renderPipeline();

        // MANUALLY handle closing (Since no Bootstrap JS exists)
        document.querySelectorAll('[data-dismiss="modal"]').forEach(btn => {
            btn.addEventListener('click', function() {
                closeModal();
            });
        });
    });

    // --- 3. MANUAL MODAL LOGIC (The Fix for "Dead Buttons") ---
    function openModal() {
        const el = document.getElementById('actionModal');
        el.style.display = 'block';
        el.style.backgroundColor = 'rgba(0,0,0,0.5)';
        el.classList.add('show');
        document.body.classList.add('modal-open');
    }

    function closeModal() {
        const el = document.getElementById('actionModal');
        el.style.display = 'none';
        el.classList.remove('show');
        document.body.classList.remove('modal-open');
    }

    // --- 4. UI LOGIC ---
    function toggleActionFields() {
        document.querySelectorAll('.action-params').forEach(el => el.style.display = 'none');
        document.getElementById('params-target').style.display = 'block'; 
        
        const type = document.getElementById('actionType').value;
        
        if (type === 'map') document.getElementById('params-map').style.display = 'block';
        if (type === 'clean') document.getElementById('params-clean').style.display = 'block';
        if (type === 'duplicate') document.getElementById('params-duplicate').style.display = 'block';

        if (type === 'save' || type === 'input') {
             document.getElementById('params-target').style.display = 'none'; 
        }
    }

    function renderPipeline() {
        const container = document.getElementById('pipelineContainer');
        if (!container) return;
        
        container.innerHTML = '';
        // Save back to hidden input
        document.getElementById('actionsJson').value = JSON.stringify(actions);

        if (!actions || actions.length === 0) {
            container.innerHTML = '<div class="text-center text-muted p-4">No actions defined. Click "Add Action" to start.</div>';
            return;
        }

        actions.forEach((action, index) => {
            let desc = `<strong>${action.type.toUpperCase()}</strong>`;
            
            if (action.type === 'map') desc += ` ${action.start}-${action.end} &rarr; <span class="text-info">${action.field}</span>`;
            else if (action.type === 'clean') desc += ` ${action.func} on <span class="text-info">${action.field}</span>`;
            // NEW: Show the behavior in the list
            else if (action.type === 'duplicate') desc += ` CHECK (${action.behavior || 'WARN'}) on <span class="text-info">${action.field}</span>`;
            else if (action.type === 'input') desc += ` <span class="text-warning">OPEN DETAILS FORM</span>`;
            else if (action.type === 'save') desc += ` <span class="text-success">COMMIT TO DATABASE</span>`;

            const div = document.createElement('div');
            div.className = 'card mb-2 bg-dark border-secondary';
            div.style.width = "100%";
            div.innerHTML = `
                <div class="card-body p-2 d-flex justify-content-between align-items-center">
                    <div class="text-white">${index + 1}. ${desc}</div>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline-secondary mr-1" onclick="moveAction(${index}, -1)" ${index === 0 ? 'disabled' : ''}>
                            <i class="fas fa-arrow-up"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary mr-2" onclick="moveAction(${index}, 1)" ${index === actions.length - 1 ? 'disabled' : ''}>
                            <i class="fas fa-arrow-down"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-info mr-1" onclick="editAction(${index})">
                            <i class="fas fa-pen"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-danger" onclick="removeAction(${index})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
                ${index < actions.length - 1 ? '<div class="connector-line" style="height:10px; background:#444; width:2px; margin:0 auto;"></div>' : ''}
            `;
            container.appendChild(div);
        });
    }

    function moveAction(index, direction) {
        const newIndex = index + direction;
        if (newIndex < 0 || newIndex >= actions.length) return;
        [actions[index], actions[newIndex]] = [actions[newIndex], actions[index]];
        renderPipeline();
    }

    function removeAction(index) {
        if(confirm('Remove this step?')) {
            actions.splice(index, 1);
            renderPipeline();
        }
    }

    // --- 5. TRIGGER FUNCTIONS ---

    function openAddModal() {
        editingIndex = -1; 
        document.getElementById('actionForm').reset();
        
        // Defaults
        document.getElementById('actionType').value = 'map';
        document.getElementById('rule_map_start').value = '1';
        document.getElementById('rule_map_end').value = '25';
        if(document.getElementById('dupBehavior')) document.getElementById('dupBehavior').value = 'WARN';
        
        document.getElementById('btnSaveAction').textContent = "Add to Pipeline";
        document.getElementById('modalTitle').textContent = "Add Pipeline Action";
        
        toggleActionFields();
        openModal(); 
    }

    function editAction(index) {
        editingIndex = index; 
        const action = actions[index];
        
        document.getElementById('actionType').value = action.type;
        toggleActionFields();
        
        if (action.type === 'map') {
            document.getElementById('rule_map_start').value = action.start || 1;
            document.getElementById('rule_map_end').value = action.end || 25;
            document.getElementById('targetField').value = action.field || '';
        } else if (action.type === 'clean') {
            document.getElementById('cleanFunc').value = action.func || 'TRIM';
            document.getElementById('targetField').value = action.field || '';
        } else if (action.type === 'duplicate') {
            document.getElementById('targetField').value = action.field || '';
            // NEW: Load Behavior
            if(document.getElementById('dupBehavior')) {
                document.getElementById('dupBehavior').value = action.behavior || 'WARN';
            }
        }
        
        document.getElementById('btnSaveAction').textContent = "Update Action";
        document.getElementById('modalTitle').textContent = `Edit Action #${index + 1}`;
        
        openModal(); 
    }

    function saveAction() {
        const type = document.getElementById('actionType').value;
        let actionObj = { type: type };

        if (type === 'map') {
            actionObj.start = document.getElementById('rule_map_start').value;
            actionObj.end = document.getElementById('rule_map_end').value;
            actionObj.field = document.getElementById('targetField').value;
            if(!actionObj.start || !actionObj.end || !actionObj.field) return alert("Missing fields");
        } 
        else if (type === 'clean') {
            actionObj.func = document.getElementById('cleanFunc').value;
            actionObj.field = document.getElementById('targetField').value;
            if(!actionObj.field) return alert("Missing target field");
        }
        else if (type === 'duplicate') {
             actionObj.field = document.getElementById('targetField').value;
             // NEW: Save Behavior
             if(document.getElementById('dupBehavior')) {
                actionObj.behavior = document.getElementById('dupBehavior').value;
             } else {
                actionObj.behavior = 'WARN';
             }
             if(!actionObj.field) return alert("Missing field to check");
        }

        if (editingIndex > -1) {
            actions[editingIndex] = actionObj;
        } else {
            actions.push(actionObj);
        }

        closeModal(); 
        renderPipeline();
    }
</script>
{% endblock %}