{% extends 'base/layout.html' %}
{% load helpers %}

{% block content %}
<div class="container-fluid">
    <h1>Manage Scheduled Jobs</h1>
    <p class="text-muted">Create and manage automated synchronization schedules using NetBox's native job system.</p>

    <!-- Active Scheduled Jobs - Show First -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: #ffffff;">
                    <strong><i class="mdi mdi-clock-check"></i> Active Scheduled Jobs</strong>
                    <span class="badge bg-light text-dark ms-2">{{ scheduled_jobs|length }}</span>
                </div>
                <div class="card-body">
                    {% if scheduled_jobs %}
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Interval</th>
                                        <th>Next Run</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for job in scheduled_jobs %}
                                    <tr>
                                        <td>
                                            <strong>{{ job.name }}</strong><br>
                                            <small class="text-muted">Created {{ job.created|date:"Y-m-d H:i" }}</small>
                                        </td>
                                        <td>
                                            {% if job.interval %}
                                                Every {{ job.interval }} min
                                            {% else %}
                                                Run Once
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if job.scheduled %}
                                                {{ job.scheduled|date:"Y-m-d H:i" }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <span class="badge bg-success">Active</span>
                                        </td>
                                        <td>
                                            <a href="{% url 'plugins:netbox_meraki:scheduled_sync_edit' pk=job.pk %}" class="btn btn-sm btn-primary" title="Edit">
                                                <i class="mdi mdi-pencil"></i>
                                            </a>
                                            <!-- NetBox 4.4.x doesn't support enable/disable - jobs are active when scheduled -->
                                            <form method="post" action="{% url 'plugins:netbox_meraki:scheduled_sync_delete' pk=job.pk %}" class="d-inline" onsubmit="return confirm('Delete this scheduled job?');">
                                                {% csrf_token %}
                                                <button type="submit" class="btn btn-sm btn-danger" title="Delete">
                                                    <i class="mdi mdi-delete"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="alert alert-info mb-0">
                            <i class="mdi mdi-information"></i> No scheduled jobs configured yet. Create one using the form below.
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Create Scheduled Job Form -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <strong><i class="mdi mdi-plus"></i> Create Scheduled Job</strong>
                </div>
                <div class="card-body">
                    {% if not can_schedule %}
                    <div class="alert" style="background-color: #f8d7da; color: #842029; border: 1px solid #f5c2c7; padding: 15px; border-radius: 5px;">
                        <i class="mdi mdi-alert"></i>
                        <strong>Scheduled sync requires NetBox 4.0 or higher.</strong>
                        <p class="mb-0">
                            Your NetBox version does not support scheduled jobs. 
                            Please use <a href="{% url 'plugins:netbox_meraki:sync' %}" style="color: #842029; text-decoration: underline; font-weight: bold;">manual sync</a> instead.
                        </p>
                        {% if exception_details %}
                        <details class="mt-3">
                            <summary style="cursor: pointer; font-weight: bold;">Debug Information</summary>
                            <pre style="background-color: #f8f9fa; padding: 10px; border-radius: 3px; margin-top: 10px; font-size: 0.85em; color: #212529;">{% for detail in exception_details %}{{ detail }}
{% endfor %}</pre>
                        </details>
                        {% endif %}
                    </div>
                    {% endif %}
                    
                    <form method="post" id="schedule-form"{% if not can_schedule %} style="display: none;"{% endif %}>
                        {% csrf_token %}
                        
                        <div class="mb-3">
                            <label for="id_name" class="form-label">Job Name *</label>
                            {{ form.name }}
                            {% if form.name.errors %}
                                <div class="invalid-feedback d-block">{{ form.name.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.name.help_text }}</small>
                        </div>

                        <div class="mb-3">
                            <label for="id_interval" class="form-label">Frequency *</label>
                            {{ form.interval }}
                            {% if form.interval.errors %}
                                <div class="invalid-feedback d-block">{{ form.interval.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.interval.help_text }}</small>
                        </div>

                        <div class="mb-3" id="custom-interval-group" style="display: none;">
                            <label for="id_custom_interval" class="form-label">Custom Interval (minutes)</label>
                            {{ form.custom_interval }}
                            {% if form.custom_interval.errors %}
                                <div class="invalid-feedback d-block">{{ form.custom_interval.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.custom_interval.help_text }}</small>
                        </div>

                        <div class="mb-3">
                            <label for="scheduled_time" class="form-label">Start Date & Time (Optional)</label>
                            {{ form.scheduled_time }}
                            {% if form.scheduled_time.errors %}
                                <div class="invalid-feedback d-block">{{ form.scheduled_time.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.scheduled_time.help_text }}</small>
                        </div>

                        <div class="mb-3">
                            <label for="id_sync_mode" class="form-label">Sync Mode *</label>
                            {{ form.sync_mode }}
                            {% if form.sync_mode.errors %}
                                <div class="invalid-feedback d-block">{{ form.sync_mode.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.sync_mode.help_text }}</small>
                        </div>

                        <div class="mb-3">
                            <label for="organization_id" class="form-label">Organization (Optional)</label>
                            {{ form.organization_id }}
                            <div id="network-count-badge" style="display: none; margin-top: 8px;">
                                <span class="badge" style="background-color: #0d6efd; color: #fff; font-weight: 600;">
                                    <i class="mdi mdi-network"></i> <span id="network-count">0</span> Networks
                                </span>
                            </div>
                            {% if form.organization_id.errors %}
                                <div class="invalid-feedback d-block">{{ form.organization_id.errors.0 }}</div>
                            {% endif %}
                            <small class="form-text text-muted">{{ form.organization_id.help_text }}</small>
                        </div>

                        <div class="mb-3" id="network-select-container" style="display: none;">
                            <label class="form-label"><strong>Networks</strong></label>
                            <div class="form-check mb-2">
                                {{ form.sync_all_networks }}
                                <label class="form-check-label" for="sync_all_networks_scheduled">
                                    Sync all networks in organization
                                </label>
                            </div>
                            <div id="network-list-container" style="display: none;">
                                <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                                    <div id="network-list-scheduled" class="mb-0">
                                        <div class="text-muted text-center py-3">
                                            <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                            Loading networks...
                                        </div>
                                    </div>
                                </div>
                                <div id="selected-network-count-scheduled" style="display: none; margin-top: 8px;">
                                    <span class="badge" style="background-color: #198754; color: #fff; font-weight: 600;">
                                        <i class="mdi mdi-checkbox-marked-circle"></i> <span id="selected-count-scheduled">0</span> selected
                                    </span>
                                </div>
                                <small class="form-text text-muted">Select specific networks to sync</small>
                            </div>
                        </div>

                        <!-- Note: NetBox 4.4.x doesn't support job enable/disable -->
                        <!-- Jobs are active when created, stopped by deletion only -->

                        <button type="submit" class="btn btn-primary">
                            <i class="mdi mdi-check"></i> Create Scheduled Job
                        </button>
                    </form>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header">
                    <strong><i class="mdi mdi-information"></i> About NetBox Native Scheduling</strong>
                </div>
                <div class="card-body">
                    <p>Scheduled jobs are managed by NetBox's built-in job system:</p>
                    <ul class="mb-0">
                        <li>Jobs appear in <strong>Jobs → Scheduled Jobs</strong></li>
                        <li>Execution history in <strong>Jobs → Job Results</strong></li>
                        <li>Automatic retry on failure</li>
                        <li>Detailed logs for each run</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Quick Guide -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <strong><i class="mdi mdi-help-circle"></i> Quick Guide</strong>
                </div>
                <div class="card-body">
                    <h6>Recommended Intervals:</h6>
                    <ul>
                        <li><strong>Run Once:</strong> Execute immediately, no recurring</li>
                        <li><strong>Hourly (60 min):</strong> For critical infrastructure</li>
                        <li><strong>Every 6 Hours (360 min):</strong> Balanced approach</li>
                        <li><strong>Daily (1440 min):</strong> Most common</li>
                        <li><strong>Weekly (10080 min):</strong> For stable environments</li>
                    </ul>
                    <hr>
                    <h6>Sync Modes:</h6>
                    <ul class="mb-0">
                        <li><strong>Auto:</strong> Changes apply immediately</li>
                        <li><strong>Review:</strong> Stage for manual approval</li>
                        <li><strong>Dry Run:</strong> Preview only, no changes</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const intervalSelect = document.getElementById('id_interval');
    const customIntervalGroup = document.getElementById('custom-interval-group');
    const organizationSelect = document.getElementById('organization_id');
    const networkCountBadge = document.getElementById('network-count-badge');
    const networkCountSpan = document.getElementById('network-count');
    const networkSelectContainer = document.getElementById('network-select-container');
    const syncAllCheckbox = document.getElementById('sync_all_networks_scheduled');
    const networkListContainer = document.getElementById('network-list-container');
    const networkList = document.getElementById('network-list-scheduled');
    
    function toggleCustomInterval() {
        if (intervalSelect.value === 'custom') {
            customIntervalGroup.style.display = 'block';
        } else {
            customIntervalGroup.style.display = 'none';
        }
    }
    
    function fetchNetworkCount() {
        const orgId = organizationSelect.value.trim();
        
        if (!orgId) {
            networkCountBadge.style.display = 'none';
            networkSelectContainer.style.display = 'none';
            return;
        }
        
        // Show loading state
        networkCountSpan.textContent = '...';
        networkCountBadge.style.display = 'block';
        
        fetch(`{% url 'plugins:netbox_meraki:get_organizations' %}`)
            .then(response => response.json())
            .then(data => {
                const org = data.organizations.find(o => o.id === orgId);
                if (org) {
                    networkCountSpan.textContent = org.network_count || 0;
                    networkCountBadge.style.display = 'block';
                    networkSelectContainer.style.display = 'block';
                    
                    // Load networks for selection
                    loadNetworks(orgId);
                }
            })
            .catch(error => {
                console.error('Error fetching organization info:', error);
                networkCountBadge.style.display = 'none';
            });
    }
    
    function loadNetworks(orgId) {
        if (!orgId) return;
        
        // Show loading state
        networkList.innerHTML = '<div class="text-muted text-center py-3"><span class="spinner-border spinner-border-sm me-2" role="status"></span>Loading networks...</div>';
        networkListContainer.style.display = 'none';
        
        fetch(`{% url 'plugins:netbox_meraki:get_networks' org_id=0 %}`.replace('/0/', `/${orgId}/`))
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    networkList.innerHTML = `
                        <div class="alert alert-danger mb-0">
                            <strong>Error:</strong> ${data.error}
                        </div>
                    `;
                    networkListContainer.style.display = 'block';
                    return;
                }
                
                const networks = data.networks || [];
                
                if (networks.length === 0) {
                    networkList.innerHTML = '<div class="text-muted text-center py-3">No networks found in this organization</div>';
                    networkListContainer.style.display = 'block';
                    return;
                }
                
                // Build network checkboxes with details
                let html = '';
                networks.forEach(network => {
                    const productTypes = network.productTypes ? network.productTypes.join(', ') : 'Unknown';
                    const tags = network.tags && network.tags.length > 0 
                        ? `<span class="badge bg-secondary ms-2">${network.tags.join(', ')}</span>`
                        : '';
                    
                    html += `
                        <div class="form-check">
                            <input class="form-check-input network-checkbox" type="checkbox" 
                                   name="network_ids" value="${network.id}" id="network_${network.id}">
                            <label class="form-check-label" for="network_${network.id}">
                                <strong>${network.name}</strong>
                                <small class="text-muted ms-2">(${productTypes})</small>
                                ${tags}
                            </label>
                        </div>
                    `;
                });
                
                networkList.innerHTML = html;
                
                // Add event listeners to checkboxes
                document.querySelectorAll('.network-checkbox').forEach(checkbox => {
                    checkbox.addEventListener('change', updateSelectedCount);
                });
                
                networkListContainer.style.display = 'block';
            })
            .catch(error => {
                console.error('Error loading networks:', error);
                networkList.innerHTML = `
                    <div class="alert alert-danger mb-0">
                        <strong>Error:</strong> Failed to load networks. Please try again.
                    </div>
                `;
                networkListContainer.style.display = 'block';
            });
    }
    
    function toggleNetworkList() {
        if (syncAllCheckbox && syncAllCheckbox.checked) {
            networkListContainer.style.display = 'none';
        } else {
            networkListContainer.style.display = 'block';
        }
    }
    
    function updateSelectedCount() {
        const selectedCheckboxes = document.querySelectorAll('.network-checkbox:checked');
        const count = selectedCheckboxes.length;
        const countBadge = document.getElementById('selected-network-count-scheduled');
        const countSpan = document.getElementById('selected-count-scheduled');
        
        if (count > 0) {
            countSpan.textContent = count;
            countBadge.style.display = 'block';
            // Auto-uncheck "sync all networks" when specific networks are selected
            if (syncAllCheckbox) {
                syncAllCheckbox.checked = false;
            }
        } else {
            countBadge.style.display = 'none';
            // Auto-check "sync all networks" when no networks are selected
            if (syncAllCheckbox) {
                syncAllCheckbox.checked = true;
            }
        }
    }
    
    intervalSelect.addEventListener('change', toggleCustomInterval);
    organizationSelect.addEventListener('change', fetchNetworkCount);
    
    if (syncAllCheckbox) {
        syncAllCheckbox.addEventListener('change', toggleNetworkList);
        toggleNetworkList();
    }
    
    toggleCustomInterval();
});
</script>
{% endblock %}
