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

{% block title %}vCenter Import Dashboard{% endblock %}

{% block tabs %}
<ul class="nav nav-tabs">
    <li class="nav-item">
        <a class="nav-link {% if selected_server == 'all' %}active{% endif %}"
           href="?server=all">
            <i class="mdi mdi-view-list"></i> All
            <span class="badge bg-primary text-white ms-1">{{ vm_count }}</span>
        </a>
    </li>
    {% for server in servers %}
    <li class="nav-item">
        <a class="nav-link {% if server == selected_server %}active{% endif %}"
           href="?server={{ server }}">
            {{ server }}
            {% if cached_data|get_key:server %}
            <span class="badge bg-success text-white ms-1">{{ cached_data|get_key:server|get_key:'count' }}</span>
            {% else %}
            <span class="badge bg-secondary text-white ms-1">-</span>
            {% endif %}
        </a>
    </li>
    {% endfor %}
    <li class="nav-item">
        <a class="nav-link" href="{% url 'plugins:netbox_vcenter:compare' %}{% if selected_server and selected_server != 'all' %}?server={{ selected_server }}{% endif %}">
            <i class="mdi mdi-compare"></i> Compare
        </a>
    </li>
</ul>
{% endblock %}

{% block content %}
<div class="row mb-4">
    <!-- Connection Form -->
    <div class="col-md-5">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-connection"></i> Connect to vCenter
                </h5>
            </div>
            <div class="card-body">
                {% if mfa_enabled %}
                <div class="alert alert-warning mb-3 py-2">
                    <div><i class="mdi mdi-shield-alert"></i> <strong>{{ mfa_label }} Required</strong></div>
                    <div class="small">{{ mfa_message }}</div>
                </div>
                {% endif %}

                <!-- Error/status messages from htmx -->
                <div id="sync-status"></div>

                <form hx-post="{% url 'plugins:netbox_vcenter:sync' %}"
                      hx-target="#sync-status"
                      hx-indicator="#sync-btn"
                      class="vcenter-sync-form">
                    {% csrf_token %}

                    <div class="mb-3">
                        <label class="form-label">{{ form.server.label }}</label>
                        {{ form.server }}
                        <small class="text-muted">{{ form.server.help_text }}</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{{ form.username.label }}</label>
                        {{ form.username }}
                        <small class="text-muted">{{ form.username.help_text }}</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{{ form.password.label }}</label>
                        {{ form.password }}
                    </div>

                    <div class="mb-3 form-check">
                        {{ form.verify_ssl }}
                        <label class="form-check-label">{{ form.verify_ssl.label }}</label>
                        <br><small class="text-muted">{{ form.verify_ssl.help_text }}</small>
                    </div>

                    <button type="submit" class="btn btn-primary" id="sync-btn">
                        <span id="sync-loading" class="htmx-indicator">
                            <span class="spinner-border spinner-border-sm me-1" role="status"></span>
                            Connecting...
                        </span>
                        <span class="sync-ready">
                            <i class="mdi mdi-sync"></i> Connect & Sync
                        </span>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Cache Status -->
    <div class="col-md-7">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-database"></i> Cache Status
                </h5>
            </div>
            <div class="card-body">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>vCenter Server</th>
                            <th>VMs</th>
                            <th>Last Sync</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for server in servers %}
                        {% with data=cached_data|get_key:server %}
                        <tr{% if server == selected_server %} class="table-active"{% endif %}>
                            <td>
                                <a href="?server={{ server }}">{{ server }}</a>
                            </td>
                            <td>
                                {% if data %}
                                <span class="badge bg-primary text-white">{{ data.count }} VMs</span>
                                {% else %}
                                <span class="text-muted">Not synced</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if data.timestamp %}
                                {{ data.timestamp|slice:":19" }}
                                {% else %}
                                <span class="text-muted">Never</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if data %}
                                <a href="{% url 'plugins:netbox_vcenter:refresh' server %}"
                                   class="btn btn-sm btn-outline-secondary"
                                   onclick="return confirm('Clear cache for {{ server }}? You will need to re-enter credentials.');">
                                    <i class="mdi mdi-refresh"></i> Clear Cache
                                </a>
                                {% endif %}
                            </td>
                        </tr>
                        {% endwith %}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Sync Loading Indicator (shown during htmx request) -->
<div id="sync-loading-panel" class="card mb-4">
    <div class="card-body">
        <div class="d-flex justify-content-center align-items-center py-5">
            <div class="text-center">
                <div class="spinner-border text-primary mb-3" role="status" style="width: 3rem; height: 3rem;">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="text-muted mb-0">Connecting to vCenter and fetching VMs...</p>
                <p class="text-muted small">This may take a moment if MFA is required.</p>
            </div>
        </div>
    </div>
</div>

<!-- VM List -->
{% if vms %}
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
            <i class="mdi mdi-server"></i>
            {% if selected_server == 'all' %}All Virtual Machines{% else %}Virtual Machines from {{ selected_server }}{% endif %}
            <span class="badge bg-info text-white ms-2">{{ vm_count }} VMs</span>
        </h5>
        <button type="button" class="btn btn-success" id="import-selected-btn" disabled>
            <i class="mdi mdi-import"></i> Import Selected to NetBox
        </button>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-striped mb-0" id="vm-table">
                <thead class="table-light">
                    <tr>
                        <th style="width: 40px;">
                            <input type="checkbox" id="select-all" class="form-check-input">
                        </th>
                        <th>Name</th>
                        {% if selected_server == 'all' %}<th>Server</th>{% endif %}
                        <th>Power</th>
                        <th>IP Address</th>
                        <th>vCPUs</th>
                        <th>Memory</th>
                        <th>Disk</th>
                        <th>Cluster</th>
                        <th>NetBox</th>
                    </tr>
                </thead>
                <tbody>
                    {% for vm in vms %}
                    <tr>
                        <td>
                            <input type="checkbox" class="form-check-input vm-checkbox"
                                   value="{{ vm.name }}" data-vm-name="{{ vm.name }}" data-server="{{ vm.source_server }}">
                        </td>
                        <td>
                            <strong>{{ vm.name }}</strong>
                            {% if vm.guest_os %}
                            <br><small class="text-muted">{{ vm.guest_os }}</small>
                            {% endif %}
                        </td>
                        {% if selected_server == 'all' %}
                        <td><small>{{ vm.source_server }}</small></td>
                        {% endif %}
                        <td>
                            {% if vm.power_state == 'on' %}
                            <span class="badge bg-success text-white">ON</span>
                            {% else %}
                            <span class="badge bg-secondary text-white">OFF</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if vm.primary_ip %}
                            <code>{{ vm.primary_ip }}</code>
                            {% else %}
                            <span class="text-muted">-</span>
                            {% endif %}
                        </td>
                        <td>{{ vm.vcpus|default:'-' }}</td>
                        <td>
                            {% if vm.memory_mb %}
                            {{ vm.memory_mb|floatformat:0 }} MB
                            {% else %}
                            -
                            {% endif %}
                        </td>
                        <td>
                            {% if vm.disk_gb %}
                            {{ vm.disk_gb }} GB
                            {% else %}
                            -
                            {% endif %}
                        </td>
                        <td>{{ vm.cluster|default:'-' }}</td>
                        <td>
                            {% if vm.exists_in_netbox %}
                            <span class="badge bg-info text-white" title="Already in NetBox">
                                <i class="mdi mdi-check"></i> Exists
                            </span>
                            {% else %}
                            <span class="badge bg-warning text-dark" title="Not in NetBox - can import">
                                <i class="mdi mdi-alert"></i> Missing
                            </span>
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% elif selected_server == 'all' and vm_count == 0 %}
<div class="alert alert-info">
    <i class="mdi mdi-information"></i>
    No cached data from any server. Select a server tab and enter credentials to sync.
</div>
{% elif selected_server and selected_server != 'all' and not cached_data|get_key:selected_server %}
<div class="alert alert-info">
    <i class="mdi mdi-information"></i> No cached data for <strong>{{ selected_server }}</strong>. Enter your credentials and click "Connect & Sync" to fetch VMs.
</div>
{% endif %}

<style>
/* htmx indicator on the sync button */
#sync-btn .htmx-indicator { display: none; }
#sync-btn.htmx-request .htmx-indicator { display: inline; }
#sync-btn.htmx-request .sync-ready { display: none; }
#sync-btn.htmx-request { pointer-events: none; opacity: 0.7; }
/* Disable form inputs while syncing */
.vcenter-sync-form:has(#sync-btn.htmx-request) input,
.vcenter-sync-form:has(#sync-btn.htmx-request) select { pointer-events: none; opacity: 0.7; }
/* Loading panel - hidden by default, shown during sync */
#sync-loading-panel { display: none; }
body:has(#sync-btn.htmx-request) #sync-loading-panel { display: block; }
/* Hide "no cached data" alerts during sync */
body:has(#sync-btn.htmx-request) .alert-info { display: none; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.vm-checkbox');
    const importBtn = document.getElementById('import-selected-btn');

    function updateImportButton() {
        const selected = document.querySelectorAll('.vm-checkbox:checked');
        importBtn.disabled = selected.length === 0;
        importBtn.textContent = selected.length > 0
            ? `Import ${selected.length} VM(s) to NetBox`
            : 'Import Selected to NetBox';
    }

    if (selectAll) {
        selectAll.addEventListener('change', function() {
            checkboxes.forEach(cb => cb.checked = this.checked);
            updateImportButton();
        });
    }

    checkboxes.forEach(cb => {
        cb.addEventListener('change', updateImportButton);
    });

    if (importBtn) {
        importBtn.addEventListener('click', function() {
            const selectedCheckboxes = Array.from(document.querySelectorAll('.vm-checkbox:checked'));

            if (selectedCheckboxes.length === 0) {
                alert('Please select at least one VM to import.');
                return;
            }

            // Group VMs by server
            const vmsByServer = {};
            selectedCheckboxes.forEach(cb => {
                const server = cb.dataset.server;
                if (!vmsByServer[server]) vmsByServer[server] = [];
                vmsByServer[server].push(cb.value);
            });

            const servers = Object.keys(vmsByServer);
            if (servers.length > 1) {
                alert('Selected VMs are from multiple servers. Please select VMs from one server at a time, or use individual server tabs.');
                return;
            }

            const server = servers[0];
            const vmsJson = encodeURIComponent(JSON.stringify(vmsByServer[server]));
            window.location.href = `{% url 'plugins:netbox_vcenter:import' %}?vms=${vmsJson}&server=${server}`;
        });
    }
});
</script>
{% endblock %}
