{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-cogs me-2"></i>Extraction Management
            <small class="text-muted">Configure outcome associations and time limits</small>
        </h1>
    </div>
</div>

<!-- UNDER/OVER Configuration -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-clock me-2"></i>UNDER/OVER Time Configuration
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-stopwatch me-2"></i>Time Limit
                            </span>
                            <input type="number" class="form-control" id="under-over-time-limit"
                                   placeholder="90" min="1" max="300" step="1" value="90">
                            <span class="input-group-text">seconds</span>
                            <button class="btn btn-outline-primary" id="btn-save-time-limit">
                                <i class="fas fa-save me-1"></i>Save
                            </button>
                        </div>
                        <small class="text-muted mt-1 d-block">
                            Time limit between UNDER and OVER outcomes (1-300 seconds)
                        </small>
                    </div>
                    <div class="col-md-6">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>UNDER/OVER Outcomes:</strong> These outcomes appear above the main extraction area
                            and have a configurable time limit between them.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Extraction Results Layout -->
<div class="row">
    <!-- Available Outcomes Pool -->
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-list me-2"></i>Available Outcomes
                </h5>
            </div>
            <div class="card-body">
                <div id="outcomes-pool" class="extraction-pool">
                    <!-- Outcomes will be loaded here -->
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading outcomes...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Extraction Result Columns -->
    <div class="col-md-8">
        <div class="row">
            <!-- WIN1 Column -->
            <div class="col-md-4 mb-3">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h6 class="card-title mb-0">
                            <i class="fas fa-trophy me-2"></i>WIN1
                        </h6>
                    </div>
                    <div class="card-body">
                        <div id="win1-column" class="extraction-column" data-result="WIN1">
                            <div class="text-center text-muted">
                                <small>Drop outcomes here</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- X Column -->
            <div class="col-md-4 mb-3">
                <div class="card">
                    <div class="card-header bg-secondary text-white">
                        <h6 class="card-title mb-0">
                            <i class="fas fa-equals me-2"></i>X
                        </h6>
                    </div>
                    <div class="card-body">
                        <div id="x-column" class="extraction-column" data-result="X">
                            <div class="text-center text-muted">
                                <small>Drop outcomes here</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- WIN2 Column -->
            <div class="col-md-4 mb-3">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h6 class="card-title mb-0">
                            <i class="fas fa-trophy me-2"></i>WIN2
                        </h6>
                    </div>
                    <div class="card-body">
                        <div id="win2-column" class="extraction-column" data-result="WIN2">
                            <div class="text-center text-muted">
                                <small>Drop outcomes here</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Trash Bin -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body text-center">
                        <div id="trash-bin" class="trash-bin">
                            <i class="fas fa-trash-alt fa-2x text-danger"></i>
                            <div class="mt-2">
                                <strong>Drop to Remove Association</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Current Associations Display -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-link me-2"></i>Current Associations
                </h5>
            </div>
            <div class="card-body">
                <div id="associations-display">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading associations...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<style>
.extraction-pool, .extraction-column {
    min-height: 200px;
    border: 2px dashed #dee2e6;
    border-radius: 0.375rem;
    padding: 1rem;
    background-color: #f8f9fa;
}

.extraction-outcome {
    display: inline-block;
    background-color: #ffffff;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    padding: 0.5rem 0.75rem;
    margin: 0.25rem;
    cursor: move;
    user-select: none;
    transition: all 0.2s ease;
    position: relative;
}

.extraction-outcome:hover {
    background-color: #e9ecef;
    border-color: #adb5bd;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.extraction-outcome.dragging {
    opacity: 0.5;
    transform: rotate(5deg);
}

/* Visual indicators for association counts */
.extraction-outcome.has-associations {
    border-left: 4px solid #28a745;
}

.extraction-outcome.max-associations {
    border-left: 4px solid #ffc107;
    background-color: #fff3cd;
}

.extraction-outcome .association-count {
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: #007bff;
    color: white;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

.extraction-outcome.max-associations .association-count {
    background-color: #ffc107;
    color: #000;
}

/* Column outcome styling - different from pool outcomes */
.extraction-outcome.in-column {
    background-color: #e7f3ff;
    border-color: #007bff;
    position: relative;
}

.extraction-outcome.in-column:hover {
    background-color: #cce7ff;
}

.extraction-outcome.in-column .remove-btn {
    position: absolute;
    top: -5px;
    right: -5px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #dc3545;
    color: white;
    border: none;
    font-size: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.trash-bin {
    border: 2px dashed #dc3545;
    border-radius: 0.375rem;
    padding: 2rem;
    background-color: #f8d7da;
    transition: all 0.2s ease;
}

.trash-bin:hover {
    background-color: #f5c6cb;
    border-color: #c82333;
}

.extraction-column.drop-target {
    border-color: #007bff;
    background-color: #e7f3ff;
}

.extraction-column.drop-invalid {
    border-color: #dc3545;
    background-color: #f8d7da;
}

.trash-bin.drop-target {
    border-color: #dc3545;
    background-color: #f5c6cb;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let draggedElement = null;
    let draggedOutcome = null;
    let currentAssociations = []; // Track current associations

    // Load data on page load
    loadAvailableOutcomes();
    loadCurrentAssociations();
    loadTimeLimitConfig();

    // Time limit save button
    document.getElementById('btn-save-time-limit').addEventListener('click', function() {
        saveTimeLimitConfig();
    });

    // Drag and drop functionality
    setupDragAndDrop();

    // Click handler for individual remove buttons in columns
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            const outcomeElement = e.target.closest('.extraction-outcome');
            const outcomeName = outcomeElement.dataset.outcome;
            const column = e.target.closest('.extraction-column');
            const extractionResult = column.dataset.result;
            
            removeSpecificAssociation(outcomeName, extractionResult);
        }
    });

    function setupDragAndDrop() {
        // Make outcomes draggable
        document.addEventListener('dragstart', function(e) {
            if (e.target.classList.contains('extraction-outcome')) {
                draggedElement = e.target;
                draggedOutcome = e.target.dataset.outcome;
                e.target.classList.add('dragging');
            }
        });

        document.addEventListener('dragend', function(e) {
            if (e.target.classList.contains('extraction-outcome')) {
                e.target.classList.remove('dragging');
                draggedElement = null;
                draggedOutcome = null;
            }
        });

        // Setup drop zones
        document.addEventListener('dragover', function(e) {
            if (e.target.classList.contains('extraction-column') ||
                e.target.classList.contains('trash-bin') ||
                e.target.closest('.extraction-column') ||
                e.target.closest('.trash-bin')) {
                e.preventDefault();
                
                // Check if this drop would be valid for columns
                let target = e.target;
                if (e.target.closest('.extraction-column')) {
                    target = e.target.closest('.extraction-column');
                }
                
                if (target.classList.contains('extraction-column') && draggedOutcome) {
                    const extractionResult = target.dataset.result;
                    const wouldExceedLimit = getOutcomeAssociationCount(draggedOutcome) >= 2;
                    const alreadyAssociated = isOutcomeAssociatedWithResult(draggedOutcome, extractionResult);
                    
                    if (wouldExceedLimit && !alreadyAssociated) {
                        target.classList.add('drop-invalid');
                        target.classList.remove('drop-target');
                    } else if (!alreadyAssociated) {
                        target.classList.add('drop-target');
                        target.classList.remove('drop-invalid');
                    }
                } else {
                    target.classList.add('drop-target');
                }
            }
        });

        document.addEventListener('dragleave', function(e) {
            if (e.target.classList.contains('extraction-column') ||
                e.target.classList.contains('trash-bin')) {
                e.target.classList.remove('drop-target');
                e.target.classList.remove('drop-invalid');
            }
        });

        document.addEventListener('drop', function(e) {
            if (e.target.classList.contains('extraction-column') ||
                e.target.closest('.extraction-column') ||
                e.target.classList.contains('trash-bin') ||
                e.target.closest('.trash-bin')) {
                e.preventDefault();

                // Remove drop target styling
                document.querySelectorAll('.drop-target, .drop-invalid').forEach(el => {
                    el.classList.remove('drop-target');
                    el.classList.remove('drop-invalid');
                });

                if (!draggedOutcome) return;

                // Determine target
                let target = e.target;
                if (e.target.closest('.extraction-column')) {
                    target = e.target.closest('.extraction-column');
                } else if (e.target.closest('.trash-bin')) {
                    target = e.target.closest('.trash-bin');
                }

                if (target.classList.contains('extraction-column')) {
                    // Add to extraction result column
                    const extractionResult = target.dataset.result;
                    addOutcomeToResult(draggedOutcome, extractionResult);
                } else if (target.classList.contains('trash-bin')) {
                    // Remove all associations for this outcome
                    removeAllOutcomeAssociations(draggedOutcome);
                }
            }
        });
    }

    function getOutcomeAssociationCount(outcomeName) {
        return currentAssociations.filter(assoc => assoc.outcome_name === outcomeName).length;
    }

    function isOutcomeAssociatedWithResult(outcomeName, extractionResult) {
        return currentAssociations.some(assoc =>
            assoc.outcome_name === outcomeName && assoc.extraction_result === extractionResult
        );
    }

    function loadAvailableOutcomes() {
        fetch('/api/extraction/outcomes')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const pool = document.getElementById('outcomes-pool');
                pool.innerHTML = '';

                // Separate UNDER/OVER from other outcomes
                const underOverOutcomes = [];
                const regularOutcomes = [];

                data.outcomes.forEach(outcome => {
                    if (outcome === 'UNDER' || outcome === 'OVER') {
                        underOverOutcomes.push(outcome);
                    } else {
                        regularOutcomes.push(outcome);
                    }
                });

                // Display UNDER/OVER separately
                if (underOverOutcomes.length > 0) {
                    const underOverSection = document.createElement('div');
                    underOverSection.className = 'mb-3';
                    underOverSection.innerHTML = `
                        <h6 class="text-muted mb-2">
                            <i class="fas fa-clock me-1"></i>UNDER/OVER Outcomes
                        </h6>
                        <div class="alert alert-warning">
                            <small>These outcomes appear above the main extraction area with time limits.</small>
                        </div>
                    `;
                    
                    underOverOutcomes.forEach(outcome => {
                        const outcomeElement = createOutcomeElement(outcome);
                        underOverSection.appendChild(outcomeElement);
                    });
                    
                    pool.appendChild(underOverSection);
                }

                // Display regular outcomes
                if (regularOutcomes.length > 0) {
                    const regularSection = document.createElement('div');
                    regularSection.innerHTML = `
                        <h6 class="text-muted mb-2">
                            <i class="fas fa-list me-1"></i>Regular Outcomes
                        </h6>
                    `;

                    regularOutcomes.forEach(outcome => {
                        const outcomeElement = createOutcomeElement(outcome);
                        regularSection.appendChild(outcomeElement);
                    });

                    pool.appendChild(regularSection);
                }
            } else {
                document.getElementById('outcomes-pool').innerHTML =
                    '<div class="alert alert-danger">Failed to load outcomes</div>';
            }
        })
        .catch(error => {
            console.error('Error loading outcomes:', error);
            document.getElementById('outcomes-pool').innerHTML =
                '<div class="alert alert-danger">Error loading outcomes</div>';
        });
    }

    function createOutcomeElement(outcome) {
        const outcomeElement = document.createElement('div');
        outcomeElement.className = 'extraction-outcome';
        outcomeElement.draggable = true;
        outcomeElement.dataset.outcome = outcome;
        outcomeElement.textContent = outcome;

        // Add visual indicators based on association count
        const associationCount = getOutcomeAssociationCount(outcome);
        if (associationCount > 0) {
            outcomeElement.classList.add('has-associations');
            if (associationCount >= 2) {
                outcomeElement.classList.add('max-associations');
            }

            // Add association count badge
            const countBadge = document.createElement('div');
            countBadge.className = 'association-count';
            countBadge.textContent = associationCount;
            outcomeElement.appendChild(countBadge);
        }

        return outcomeElement;
    }

    function loadCurrentAssociations() {
        fetch('/api/extraction/associations')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Store current associations for validation
                currentAssociations = data.associations;
                
                // Clear existing associations from columns
                document.querySelectorAll('.extraction-column').forEach(column => {
                    const placeholder = column.querySelector('.text-center');
                    if (placeholder) {
                        column.innerHTML = '';
                        column.appendChild(placeholder);
                    } else {
                        column.innerHTML = '<div class="text-center text-muted"><small>Drop outcomes here</small></div>';
                    }
                });

                // Add outcomes to their respective columns
                data.associations.forEach(assoc => {
                    addOutcomeToColumn(assoc.outcome_name, assoc.extraction_result);
                });

                // Update associations display
                updateAssociationsDisplay(data.associations);
                
                // Refresh outcomes pool with updated association counts
                loadAvailableOutcomes();
            } else {
                document.getElementById('associations-display').innerHTML =
                    '<div class="alert alert-danger">Failed to load associations</div>';
            }
        })
        .catch(error => {
            console.error('Error loading associations:', error);
            document.getElementById('associations-display').innerHTML =
                '<div class="alert alert-danger">Error loading associations</div>';
        });
    }

    function addOutcomeToColumn(outcomeName, extractionResult) {
        const column = document.querySelector(`[data-result="${extractionResult}"]`);
        if (!column) return;

        // Remove placeholder if present (only for first outcome in column)
        const placeholder = column.querySelector('.text-center');
        if (placeholder && column.children.length === 1) {
            placeholder.remove();
        }

        // Create outcome element with remove button
        const outcomeElement = document.createElement('div');
        outcomeElement.className = 'extraction-outcome in-column';
        outcomeElement.draggable = true;
        outcomeElement.dataset.outcome = outcomeName;
        outcomeElement.textContent = outcomeName;

        // Add remove button
        const removeBtn = document.createElement('button');
        removeBtn.className = 'remove-btn';
        removeBtn.innerHTML = '×';
        removeBtn.title = `Remove ${outcomeName} from ${extractionResult}`;
        outcomeElement.appendChild(removeBtn);

        column.appendChild(outcomeElement);
    }

    function addOutcomeToResult(outcomeName, extractionResult) {
        // Check if association already exists
        if (isOutcomeAssociatedWithResult(outcomeName, extractionResult)) {
            alert(`Outcome '${outcomeName}' is already associated with ${extractionResult}`);
            return;
        }

        // Check association limit
        if (getOutcomeAssociationCount(outcomeName) >= 2) {
            alert(`Outcome '${outcomeName}' already has the maximum 2 associations`);
            return;
        }

        // Add association using new endpoint
        fetch('/api/extraction/associations/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                outcome_name: outcomeName,
                extraction_result: extractionResult
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Reload associations to reflect changes
                loadCurrentAssociations();
            } else {
                alert('Failed to add association: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error adding association:', error);
            alert('Error adding association: ' + error.message);
        });
    }

    function removeSpecificAssociation(outcomeName, extractionResult) {
        // Remove specific association using new endpoint
        fetch('/api/extraction/associations/remove', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                outcome_name: outcomeName,
                extraction_result: extractionResult
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadCurrentAssociations();
            } else {
                alert('Failed to remove association: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error removing association:', error);
            alert('Error removing association: ' + error.message);
        });
    }

    function removeAllOutcomeAssociations(outcomeName) {
        // Get all associations for this outcome and remove them one by one
        const outcomeAssociations = currentAssociations.filter(assoc => assoc.outcome_name === outcomeName);
        
        if (outcomeAssociations.length === 0) {
            alert(`No associations found for outcome '${outcomeName}'`);
            return;
        }

        // Remove each association
        let removedCount = 0;
        const totalToRemove = outcomeAssociations.length;

        outcomeAssociations.forEach(assoc => {
            fetch('/api/extraction/associations/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    outcome_name: assoc.outcome_name,
                    extraction_result: assoc.extraction_result
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    removedCount++;
                    if (removedCount === totalToRemove) {
                        // All associations removed, reload
                        loadCurrentAssociations();
                    }
                } else {
                    alert('Failed to remove association: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error removing association:', error);
                alert('Error removing association: ' + error.message);
            });
        });
    }

    function updateAssociationsDisplay(associations) {
        const display = document.getElementById('associations-display');

        if (associations.length === 0) {
            display.innerHTML = '<div class="text-center text-muted">No associations configured</div>';
            return;
        }

        // Group associations by extraction result
        const grouped = {};
        associations.forEach(assoc => {
            if (!grouped[assoc.extraction_result]) {
                grouped[assoc.extraction_result] = [];
            }
            grouped[assoc.extraction_result].push(assoc.outcome_name);
        });

        let html = '<div class="row">';
        Object.keys(grouped).forEach(result => {
            html += `
                <div class="col-md-4 mb-3">
                    <div class="card">
                        <div class="card-header">
                            <strong>${result}</strong>
                        </div>
                        <div class="card-body">
                            <div class="d-flex flex-wrap">
                                ${grouped[result].map(outcome =>
                                    `<span class="badge bg-secondary me-1 mb-1">${outcome}</span>`
                                ).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';

        display.innerHTML = html;
    }

    function loadTimeLimitConfig() {
        fetch('/api/extraction/config')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.config && data.config.under_over_time_limit) {
                document.getElementById('under-over-time-limit').value = data.config.under_over_time_limit;
            }
        })
        .catch(error => {
            console.error('Error loading time limit config:', error);
        });
    }

    function saveTimeLimitConfig() {
        const timeLimitInput = document.getElementById('under-over-time-limit');
        const timeLimitValue = parseInt(timeLimitInput.value);

        if (!timeLimitValue || timeLimitValue < 1 || timeLimitValue > 300) {
            alert('Please enter a valid time limit between 1 and 300 seconds');
            return;
        }

        const saveBtn = document.getElementById('btn-save-time-limit');
        const originalText = saveBtn.innerHTML;

        // Show loading state
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

        fetch('/api/extraction/config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                config_key: 'under_over_time_limit',
                config_value: timeLimitValue,
                value_type: 'int'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Time limit saved successfully!');
            } else {
                alert('Failed to save time limit: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error saving time limit: ' + error.message);
        })
        .finally(() => {
            // Restore button state
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    }
});
</script>
{% endblock %}