{% extends "base.html" %}

{% block title %}Admin | Instanzen{% endblock %}

{% block content %}
<section class="instance-header">
    <h1>Schul-Instanzen starten</h1>
    <p>Neue Instanzen des Inventarsystems für Subdomains pro Schule anlegen, sowie die Bibliothek dauerhaft aktivieren oder deaktivieren.</p>
</section>

<section class="dashboard-grid">
    <article class="kpi-card">
        <p class="kpi-label">Instanzen gesamt</p>
        <p class="kpi-value">{{ instance_dashboard.kpis.total }}</p>
    </article>
    <article class="kpi-card good">
        <p class="kpi-label">Laufend</p>
        <p class="kpi-value">{{ instance_dashboard.kpis.running }}</p>
    </article>
    <article class="kpi-card bad">
        <p class="kpi-label">Fehlerhaft</p>
        <p class="kpi-value">{{ instance_dashboard.kpis.error }}</p>
    </article>
    <article class="kpi-card">
        <p class="kpi-label">Bibliothek aktiv</p>
        <p class="kpi-value">{{ instance_dashboard.kpis.library_on }}</p>
    </article>
    <article class="kpi-card">
        <p class="kpi-label">Nutzer zugewiesen</p>
        <p class="kpi-value">{{ instance_dashboard.kpis.assigned_users }}</p>
    </article>
</section>

<section class="charts-grid">
    <article class="chart-card">
        <h3>Status</h3>
        <canvas id="statusChart" aria-label="Status Chart"></canvas>
    </article>
    <article class="chart-card">
        <h3>Bibliothek</h3>
        <canvas id="libraryChart" aria-label="Library Chart"></canvas>
    </article>
    <article class="chart-card wide">
        <h3>Versionen</h3>
        <canvas id="versionsChart" aria-label="Versions Chart"></canvas>
    </article>
    <article class="chart-card wide">
        <h3>Instanzen pro Nutzer</h3>
        <canvas id="ownersChart" aria-label="Owners Chart"></canvas>
    </article>
    <article class="chart-card wide">
        <h3>Aktivität (letzte 7 Tage)</h3>
        <canvas id="activityChart" aria-label="Activity Chart"></canvas>
    </article>
</section>

<section class="instance-form-wrap">
    <form method="post" class="instance-form">
        <input type="hidden" name="action" value="create">

        <label for="owner_username">Zugewiesener Nutzer</label>
        <select id="owner_username" name="owner_username" required {% if not available_users %}disabled{% endif %}>
            {% if available_users %}
                <option value="">Nutzer wählen</option>
                {% for user in available_users %}
                    <option value="{{ user.username }}" data-school-name="{{ user.display_name or user.username }}">{{ user.username }}{% if user.display_name %} - {{ user.display_name }}{% endif %}</option>
                {% endfor %}
            {% else %}
                <option value="">Keine freien Nutzer verfügbar</option>
            {% endif %}
        </select>

        {% if not available_users %}
        <p class="warn-text">Alle Nutzer sind bereits einer Instanz zugewiesen. Lege einen neuen Nutzer an oder lösche eine bestehende Instanz.</p>
        {% endif %}

        <label for="school_name">Schulname</label>
        <input id="school_name" name="school_name" type="text" placeholder="wird aus dem Nutzer übernommen" required>

        <label for="app_image_tag">Version</label>
        <select id="app_image_tag" name="app_image_tag" required>
            {% for version in version_options %}
                <option value="{{ version }}">{{ version }}</option>
            {% endfor %}
        </select>

        <label for="subdomain">Subdomain (optional)</label>
        <input id="subdomain" name="subdomain" type="text" placeholder="wird aus Schulname abgeleitet">

        <label class="check-row">
            <input type="checkbox" name="library_enabled" value="1">
            Bibliothek aktivieren
        </label>

        <button type="submit">Instanz erstellen und starten</button>
    </form>

    <aside class="instance-meta">
        <h2>Systemdaten</h2>
        <p><strong>Repository:</strong> {{ instance_repo_url }}</p>
        <p><strong>Basis-Domain:</strong> {{ parent_domain }}</p>
        <p><strong>Instanz-Pfad:</strong> {{ base_dir }}</p>
        <p><strong>Provisioning-Skript:</strong> {{ provision_script }}</p>
        <p class="note">Hinweis: Für Docker- und Nginx-Operationen benötigt der laufende Prozess die passenden Host-Berechtigungen.</p>
    </aside>
</section>

<section class="instance-table-wrap">
    <div class="table-head">
        <h2>Vorhandene Instanzen</h2>
        <div class="table-actions">
            <form method="post" class="inline-toggle-form">
                <input type="hidden" name="action" value="reload_nginx">
                <button type="submit">Nginx neu laden &amp; Status aktualisieren</button>
            </form>
            <form method="post" class="inline-toggle-form">
                <input type="hidden" name="action" value="confirm_nginx_reload">
                <button type="submit">Reload auf Host bestätigt</button>
            </form>
        </div>
    </div>
    {% if instances %}
    <table>
        <thead>
            <tr>
                <th>Schule</th>
                <th>Nutzer</th>
                <th>Subdomain</th>
                <th>Version</th>
                <th>Bibliothek</th>
                <th>Aktion</th>
                <th>HTTPS-Port</th>
                <th>Status</th>
                <th>Nginx</th>
                <th>Letzte Meldung</th>
                <th>Aktualisiert</th>
            </tr>
        </thead>
        <tbody>
            {% for item in instances %}
            <tr>
                <td>{{ item.school_name }}</td>
                <td>{{ item.owner_username or '-' }}</td>
                <td>
                    {% if item.domain %}
                        <a class="instance-domain-link" href="https://{{ item.domain }}" target="_blank" rel="noopener noreferrer">{{ item.domain }}</a>
                    {% else %}
                        -
                    {% endif %}
                </td>
                <td>{{ item.app_image_tag or 'latest' }}</td>
                <td>{{ 'an' if item.library_enabled else 'aus' }}</td>
                <td>
                    <form method="post" class="inline-toggle-form">
                        <input type="hidden" name="action" value="toggle_library">
                        <input type="hidden" name="subdomain" value="{{ item.subdomain }}">
                        <input type="hidden" name="library_enabled" value="{{ 0 if item.library_enabled else 1 }}">
                        <button type="submit">{{ 'Bibliothek deaktivieren' if item.library_enabled else 'Bibliothek aktivieren' }}</button>
                    </form>
                    <form method="post" class="inline-toggle-form" onsubmit="return confirm('Instanz {{ item.subdomain }} wirklich löschen? Dieser Vorgang entfernt Container, Daten und Konfiguration.');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="subdomain" value="{{ item.subdomain }}">
                        <button type="submit" class="danger">Instanz löschen</button>
                    </form>
                </td>
                <td>{{ item.https_port or '-' }}</td>
                <td>
                    <span class="pill {{ 'ok' if item.status == 'Läuft' else 'error' }}">{{ item.status }}</span>
                </td>
                <td>{{ item.nginx_status }}</td>
                <td>{{ item.last_message }}</td>
                <td>{{ item.updated_at }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% else %}
    <p>Noch keine Instanzen vorhanden.</p>
    {% endif %}
</section>

<style>
.instance-header {
    margin-bottom: 1rem;
}

.dashboard-grid {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 0.75rem;
    margin-bottom: 1rem;
}

.kpi-card {
    border: 1px solid #d8e1e8;
    background: linear-gradient(160deg, #ffffff 0%, #f4f8fb 100%);
    border-radius: 14px;
    padding: 0.85rem;
}

.kpi-card.good {
    border-color: #8cc9a6;
    background: linear-gradient(160deg, #ffffff 0%, #eaf8f1 100%);
}

.kpi-card.bad {
    border-color: #e3adad;
    background: linear-gradient(160deg, #ffffff 0%, #fef2f2 100%);
}

.kpi-label {
    margin: 0;
    font-size: 0.84rem;
    color: #4b6170;
    font-weight: 600;
}

.kpi-value {
    margin: 0.3rem 0 0;
    font-size: 1.58rem;
    font-weight: 800;
    color: #11364a;
}

.charts-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.85rem;
    margin-bottom: 1.2rem;
}

.chart-card {
    border: 1px solid #d8e1e8;
    background: #ffffff;
    border-radius: 14px;
    padding: 0.85rem;
}

.chart-card.wide {
    grid-column: span 2;
}

.chart-card h3 {
    margin: 0 0 0.45rem;
    font-size: 1rem;
}

.chart-card canvas {
    width: 100%;
    max-height: 260px;
}

.instance-form-wrap {
    display: grid;
    grid-template-columns: 1.2fr 1fr;
    gap: 1rem;
    margin-bottom: 1.2rem;
}

.instance-form,
.instance-meta,
.instance-table-wrap {
    border: 1px solid #d8e1e8;
    background: #ffffff;
    border-radius: 14px;
    padding: 1rem;
}

.table-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.table-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.instance-form {
    display: grid;
    gap: 0.5rem;
}

.instance-form input,
.instance-form select {
    border: 1px solid #bcd0de;
    border-radius: 10px;
    padding: 0.55rem 0.65rem;
    font: inherit;
}

.check-row {
    display: flex;
    align-items: center;
    gap: 0.45rem;
    margin-top: 0.2rem;
    font-weight: 600;
}

.instance-form button {
    margin-top: 0.4rem;
    border: none;
    border-radius: 999px;
    padding: 0.55rem 0.95rem;
    font-weight: 700;
    cursor: pointer;
    color: #ffffff;
    background: linear-gradient(120deg, #0b5b89 0%, #0b4262 100%);
}

.warn-text {
    margin: 0.2rem 0 0.1rem;
    color: #8b2a27;
    font-size: 0.9rem;
    font-weight: 600;
}

.instance-domain-link {
    color: #0b5b89;
    font-weight: 700;
    text-decoration: none;
}

.instance-domain-link:hover {
    text-decoration: underline;
}

.inline-toggle-form {
    margin: 0;
}

.inline-toggle-form + .inline-toggle-form {
    margin-top: 0.35rem;
}

.inline-toggle-form button {
    border: 1px solid #bcd0de;
    background: #ffffff;
    color: #173f5a;
    border-radius: 999px;
    padding: 0.35rem 0.68rem;
    font: inherit;
    font-weight: 700;
    cursor: pointer;
}

.inline-toggle-form button:hover {
    background: #f2f8fc;
}

.inline-toggle-form button.danger {
    border-color: #e3adad;
    color: #8b2a27;
    background: #fef2f2;
}

.inline-toggle-form button.danger:hover {
    background: #fde4e4;
}

.instance-meta h2,
.instance-table-wrap h2 {
    margin: 0 0 0.5rem;
}

.instance-meta p {
    margin: 0.28rem 0;
    font-size: 0.92rem;
}

.instance-meta .note {
    margin-top: 0.65rem;
    padding-top: 0.65rem;
    border-top: 1px dashed #c7d2db;
}

.instance-table-wrap {
    overflow-x: auto;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    text-align: left;
    border-bottom: 1px solid #e7edf3;
    padding: 0.62rem;
    vertical-align: top;
    font-size: 0.9rem;
}

.pill {
    display: inline-flex;
    border-radius: 999px;
    padding: 0.18rem 0.62rem;
    font-weight: 700;
    font-size: 0.78rem;
}

.pill.ok {
    background: #eaf8f1;
    border: 1px solid #8cc9a6;
    color: #0f5c3a;
}

.pill.error {
    background: #fef2f2;
    border: 1px solid #e3adad;
    color: #8b2a27;
}

@media (max-width: 900px) {
    .dashboard-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .charts-grid {
        grid-template-columns: 1fr;
    }

    .chart-card.wide {
        grid-column: span 1;
    }

    .instance-form-wrap {
        grid-template-columns: 1fr;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
(function() {
    const dashboardData = {{ instance_dashboard|tojson }};

    const buildChart = (id, config) => {
        const element = document.getElementById(id);
        if (!element) {
            return;
        }
        new Chart(element, config);
    };

    buildChart('statusChart', {
        type: 'doughnut',
        data: {
            labels: dashboardData.status.labels,
            datasets: [{
                data: dashboardData.status.values,
                backgroundColor: ['#3aa675', '#cf4b49', '#8aa6b8']
            }]
        },
        options: { plugins: { legend: { position: 'bottom' } } }
    });

    buildChart('libraryChart', {
        type: 'pie',
        data: {
            labels: dashboardData.library.labels,
            datasets: [{
                data: dashboardData.library.values,
                backgroundColor: ['#1b6f8e', '#c6d7e2']
            }]
        },
        options: { plugins: { legend: { position: 'bottom' } } }
    });

    buildChart('versionsChart', {
        type: 'bar',
        data: {
            labels: dashboardData.versions.labels,
            datasets: [{
                label: 'Instanzen',
                data: dashboardData.versions.values,
                backgroundColor: '#1b6f8e'
            }]
        },
        options: {
            responsive: true,
            scales: { y: { beginAtZero: true, ticks: { precision: 0 } } },
            plugins: { legend: { display: false } }
        }
    });

    buildChart('ownersChart', {
        type: 'bar',
        data: {
            labels: dashboardData.owners.labels,
            datasets: [{
                label: 'Instanzen',
                data: dashboardData.owners.values,
                backgroundColor: '#b3672e'
            }]
        },
        options: {
            indexAxis: 'y',
            scales: { x: { beginAtZero: true, ticks: { precision: 0 } } },
            plugins: { legend: { display: false } }
        }
    });

    buildChart('activityChart', {
        type: 'line',
        data: {
            labels: dashboardData.activity.labels,
            datasets: [{
                label: 'Updates',
                data: dashboardData.activity.values,
                borderColor: '#0b5b89',
                backgroundColor: 'rgba(11, 91, 137, 0.15)',
                fill: true,
                tension: 0.25
            }]
        },
        options: {
            scales: { y: { beginAtZero: true, ticks: { precision: 0 } } },
            plugins: { legend: { display: false } }
        }
    });

    const ownerSelect = document.getElementById('owner_username');
    const schoolInput = document.getElementById('school_name');
    if (!ownerSelect || !schoolInput) {
        return;
    }

    const updateSchoolName = () => {
        const selectedOption = ownerSelect.options[ownerSelect.selectedIndex];
        const schoolName = selectedOption ? (selectedOption.dataset.schoolName || '') : '';
        if (schoolName) {
            schoolInput.value = schoolName;
        }
    };

    ownerSelect.addEventListener('change', updateSchoolName);
    updateSchoolName();
})();
</script>
{% endblock %}
