{% extends 'netbox_meraki/base.html' %}
{% load static %}

{% block page_content %}
<style>
    /* Enhanced badge styling for better visibility in all modes */
    .config-badge {
        padding: 8px 16px;
        font-size: 0.95rem;
        font-weight: 600;
        border-radius: 6px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 10px;
    }
    .config-badge.success {
        background-color: #28a745;
        color: #ffffff;
        border: 2px solid #1e7e34;
    }
    .config-badge.info {
        background-color: #17a2b8;
        color: #ffffff;
        border: 2px solid #117a8b;
    }
    .config-badge.warning {
        background-color: #ffc107;
        color: #000000;
        border: 2px solid #e0a800;
    }
    .config-badge.danger {
        background-color: #dc3545;
        color: #ffffff;
        border: 2px solid #bd2130;
    }
    
    /* Status badge improvements */
    .status-badge {
        padding: 6px 14px;
        font-size: 0.9rem;
        font-weight: 600;
        border-radius: 5px;
    }
    .status-badge.success {
        background-color: #28a745;
        color: #ffffff;
    }
    .status-badge.warning {
        background-color: #ffc107;
        color: #000000;
    }
    .status-badge.danger {
        background-color: #dc3545;
        color: #ffffff;
    }
    .status-badge.info {
        background-color: #17a2b8;
        color: #ffffff;
    }
    .status-badge.running {
        background-color: #007bff;
        color: #ffffff;
    }
    
    /* Card header styling */
    .card-header.config-header {
        background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
        color: #ffffff;
        font-weight: 600;
        border: none;
    }
    .card-header.sync-header {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: #ffffff;
        font-weight: 600;
        border: none;
    }
    .card-header.action-header {
        background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
        color: #ffffff;
        font-weight: 600;
        border: none;
    }
    
    /* Configuration details */
    .config-detail {
        padding: 8px 0;
        border-bottom: 1px solid var(--bs-border-color);
    }
    .config-detail:last-child {
        border-bottom: none;
    }
    .config-detail .label {
        font-weight: 600;
        color: var(--bs-emphasis-color);
        margin-right: 8px;
    }
    .config-detail .value {
        color: var(--bs-body-color);
    }
</style>

<div class="row">
    <div class="col-md-12">
        <h1>Meraki Sync Dashboard</h1>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header config-header">
                <strong>Configuration Status</strong>
            </div>
            <div class="card-body">
                <div class="config-detail">
                    <span class="label">API Key:</span>
                    {% if api_key_configured %}
                        <span class="config-badge success">
                            <i class="mdi mdi-check-circle"></i> Configured
                        </span>
                    {% else %}
                        <span class="config-badge danger">
                            <i class="mdi mdi-alert-circle"></i> Not Configured
                        </span>
                        <p class="mt-2 text-muted small">Configure the Meraki API key in NetBox configuration.py</p>
                    {% endif %}
                </div>
                
                <div class="config-detail mt-3">
                    <span class="label">Device Roles:</span>
                    {% if device_roles_configured %}
                        <span class="config-badge info">
                            <i class="mdi mdi-cog"></i> {{ configured_roles_count }} Override{{ configured_roles_count|pluralize }}
                        </span>
                        <p class="mt-2 text-muted small">Device role names customized in configuration.py</p>
                    {% else %}
                        <span class="config-badge warning">
                            <i class="mdi mdi-information"></i> Using Defaults
                        </span>
                        <p class="mt-2 text-muted small">Using default device role names. Customize in configuration.py or web UI.</p>
                    {% endif %}
                </div>
                
                {% if has_additional_config %}
                <div class="config-detail mt-3">
                    <span class="label">Additional Settings:</span>
                    <span class="config-badge info">
                        <i class="mdi mdi-tune"></i> {{ other_configs_count }} Parameter{{ other_configs_count|pluralize }}
                    </span>
                    <p class="mt-2 text-muted small">Auto-creation, defaults, and other settings configured in configuration.py</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card">
            <div class="card-header sync-header">
                <strong>Latest Sync</strong>
            </div>
            <div class="card-body">
                {% if latest_sync %}
                    <p><strong>Time:</strong> {{ latest_sync.timestamp }}</p>
                    <p><strong>Status:</strong> 
                        <span class="status-badge success">{{ latest_sync.status|upper }}</span>
                    </p>
                    <p><strong>Devices:</strong> {{ latest_sync.devices_synced }}</p>
                    <p><strong>VLANs:</strong> {{ latest_sync.vlans_synced }}</p>
                    <p><strong>Prefixes:</strong> {{ latest_sync.prefixes_synced }}</p>
                    {% if latest_sync.deleted_devices or latest_sync.deleted_vlans or latest_sync.deleted_prefixes %}
                    <hr>
                    <p class="text-muted"><small>
                        Cleaned: {{ latest_sync.deleted_devices }} devices, 
                        {{ latest_sync.deleted_vlans }} VLANs, 
                        {{ latest_sync.deleted_prefixes }} prefixes
                    </small></p>
                    {% endif %}
                {% else %}
                    <p class="text-muted">No synchronization performed yet.</p>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card">
            <div class="card-header action-header">
                <strong>Quick Actions</strong>
            </div>
            <div class="card-body">
                <a href="{% url 'plugins:netbox_meraki:sync' %}" class="btn btn-primary w-100 mb-2">
                    <i class="mdi mdi-sync"></i> Sync Now
                </a>
                <a href="{% url 'plugins:netbox_meraki:scheduled_sync' %}" class="btn btn-success w-100 mb-2">
                    <i class="mdi mdi-clock-outline"></i> Manage Scheduled Jobs
                </a>
                <a href="{% url 'plugins:netbox_meraki:review_list' %}" class="btn btn-info w-100 mb-2">
                    <i class="mdi mdi-playlist-check"></i> View Reviews
                </a>
                <a href="{% url 'plugins:netbox_meraki:job_history' %}" class="btn btn-warning w-100 mb-2">
                    <i class="mdi mdi-history"></i> Job History
                </a>
                <a href="{% url 'plugins:netbox_meraki:config' %}" class="btn btn-secondary w-100">
                    <i class="mdi mdi-cog"></i> View Configuration
                </a>
            </div>
        </div>
    </div>
</div>

{% if running_syncs %}
<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header" style="background: linear-gradient(135deg, #ff6b6b 0%, #c92a2a 100%); color: #ffffff; font-weight: 600;">
                <strong>Running Syncs</strong>
                <span class="badge bg-light text-dark ms-2">{{ running_syncs|length }}</span>
            </div>
            <div class="card-body">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Started</th>
                            <th>Sync Mode</th>
                            <th>Progress</th>
                            <th>Current Operation</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="running-syncs-tbody">
                        {% for sync in running_syncs %}
                            <tr data-sync-id="{{ sync.pk }}" class="running-sync-row">
                                <td>{{ sync.timestamp }}</td>
                                <td>
                                    {% if sync.sync_mode == 'full' %}
                                        <span class="badge bg-primary">Full Sync</span>
                                    {% elif sync.sync_mode == 'selective' %}
                                        <span class="badge bg-info">Selective</span>
                                    {% else %}
                                        <span class="badge bg-secondary">{{ sync.sync_mode|title }}</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="progress" style="height: 24px; min-width: 150px;">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-success" 
                                             role="progressbar" 
                                             style="width: {{ sync.progress_percent|default:0 }}%"
                                             aria-valuenow="{{ sync.progress_percent|default:0 }}" 
                                             aria-valuemin="0" 
                                             aria-valuemax="100"
                                             id="progress-bar-{{ sync.pk }}">
                                            <strong>{{ sync.progress_percent|default:0 }}%</strong>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <small id="current-op-{{ sync.pk }}">{{ sync.current_operation|default:"Initializing..." }}</small>
                                </td>
                                <td>
                                    <span class="status-badge running">
                                        <i class="mdi mdi-loading mdi-spin"></i> RUNNING
                                    </span>
                                </td>
                                <td>
                                    <a href="{% url 'plugins:netbox_meraki:synclog' pk=sync.pk %}" class="btn btn-sm btn-primary">
                                        View Details
                                    </a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Auto-refresh running syncs progress every 2 seconds
(function() {
    const runningRows = document.querySelectorAll('.running-sync-row');
    
    if (runningRows.length === 0) return;
    
    function updateProgress() {
        runningRows.forEach(row => {
            const syncId = row.getAttribute('data-sync-id');
            
            fetch(`{% url 'plugins:netbox_meraki:sync_status_api' pk=0 %}`.replace('/0/', `/${syncId}/`))
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        console.error('Error fetching progress:', data.error);
                        return;
                    }
                    
                    // Update progress bar
                    const progressBar = document.getElementById(`progress-bar-${syncId}`);
                    if (progressBar) {
                        progressBar.style.width = data.progress_percent + '%';
                        progressBar.setAttribute('aria-valuenow', data.progress_percent);
                        progressBar.innerHTML = `<strong>${data.progress_percent}%</strong>`;
                    }
                    
                    // Update current operation
                    const currentOp = document.getElementById(`current-op-${syncId}`);
                    if (currentOp && data.current_operation) {
                        currentOp.textContent = data.current_operation;
                    }
                    
                    // If sync completed, reload page to update UI
                    if (!data.is_running) {
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error('Error updating progress:', error);
                });
        });
    }
    
    // Update immediately
    updateProgress();
    
    // Then update every 2 seconds
    const intervalId = setInterval(updateProgress, 2000);
    
    // Clear interval when leaving page
    window.addEventListener('beforeunload', () => {
        clearInterval(intervalId);
    });
})();
</script>
{% endif %}

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <strong>Recent Sync Logs</strong>
            </div>
            <div class="card-body">
                {% if recent_logs %}
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Timestamp</th>
                                <th>Status</th>
                                <th>Organizations</th>
                                <th>Networks</th>
                                <th>Devices</th>
                                <th>VLANs</th>
                                <th>Prefixes</th>
                                <th>Duration</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for log in recent_logs %}
                                <tr>
                                    <td>{{ log.timestamp }}</td>
                                    <td>
                                        {% if log.status == 'success' %}
                                            <span class="status-badge success">{{ log.status|upper }}</span>
                                        {% elif log.status == 'partial' %}
                                            <span class="status-badge warning">{{ log.status|upper }}</span>
                                        {% elif log.status == 'failed' %}
                                            <span class="status-badge danger">{{ log.status|upper }}</span>
                                        {% elif log.status == 'running' %}
                                            <span class="status-badge running">{{ log.status|upper }}</span>
                                        {% else %}
                                            <span class="status-badge info">{{ log.status|upper }}</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ log.organizations_synced }}</td>
                                    <td>{{ log.networks_synced }}</td>
                                    <td>{{ log.devices_synced }}</td>
                                    <td>{{ log.vlans_synced }}</td>
                                    <td>{{ log.prefixes_synced }}</td>
                                    <td>
                                        {% if log.duration_seconds %}
                                            {{ log.duration_seconds|floatformat:2 }}s
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td>
                                        <a href="{% url 'plugins:netbox_meraki:synclog' pk=log.pk %}" class="btn btn-sm btn-primary">
                                            View Details
                                        </a>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                {% else %}
                    <p class="text-muted">No sync logs available.</p>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Scheduled Jobs Section -->
<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%); color: #ffffff; font-weight: 600;">
                <strong>Scheduled Sync Jobs</strong>
                {% if scheduled_jobs_count %}
                    <span class="badge bg-light text-dark ms-2">{{ scheduled_jobs_count }} Total</span>
                {% endif %}
            </div>
            <div class="card-body">
                {% if scheduled_jobs %}
                    <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>
                                        {% if job.description %}
                                            <br><small class="text-muted">{{ job.description }}</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if job.interval %}
                                            Every {{ job.interval }} minutes
                                        {% else %}
                                            <span class="text-muted">One-time</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if job.scheduled %}
                                            {{ job.scheduled }}
                                        {% else %}
                                            <span class="text-muted">Pending</span>
                                        {% endif %}
                                    </td>
                                    <parameter name="td">
                                        <span class="badge bg-success">
                                            <i class="mdi mdi-check-circle"></i> Active
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <!-- Edit Button -->
                                            <a href="{% url 'plugins:netbox_meraki:scheduled_sync_edit' pk=job.pk %}" 
                                               class="btn btn-sm btn-primary" 
                                               title="Edit Schedule">
                                                <i class="mdi mdi-pencil"></i> Edit
                                            </a>
                                            
                                            <!-- Play/Pause Button - NetBox 4.4.x doesn't support enable/disable -->
                                            <!-- Jobs are active if scheduled, delete to stop -->
                                            
                                            <!-- Delete Button -->
                                            <form method="post" 
                                                  action="{% url 'plugins:netbox_meraki:scheduled_sync_delete' pk=job.pk %}" 
                                                  style="display: inline;"
                                                  onsubmit="return confirm('Are you sure you want to delete this scheduled job?');">
                                                {% csrf_token %}
                                                <button type="submit" 
                                                        class="btn btn-sm btn-danger" 
                                                        title="Delete Job">
                                                    <i class="mdi mdi-delete"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                    {% if scheduled_jobs_count > 5 %}
                        <div class="text-center mt-3">
                            <p class="text-muted">Showing 5 most recent of {{ scheduled_jobs_count }} scheduled jobs</p>
                            <a href="{% url 'plugins:netbox_meraki:scheduled_sync' %}" class="btn btn-outline-primary">
                                <i class="mdi mdi-clock-outline"></i> View All Scheduled Jobs
                            </a>
                        </div>
                    {% endif %}
                {% else %}
                    <p class="text-muted">No scheduled jobs configured.</p>
                    <a href="{% url 'plugins:netbox_meraki:scheduled_sync' %}" class="btn btn-primary">
                        <i class="mdi mdi-plus-circle"></i> Create Scheduled Job
                    </a>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}
