{% extends "frontend/base.html" %}
{% load i18n static pprint_filters %}
{% block html_title %}
    {% block page_title %}
        {{ instance.display_name }}
    {% endblock page_title %}
{% endblock html_title %}
{% block page_title_extra %}
    <div>
        {% if instance.fqdn_url %}
            <a href="https://{{ instance.fqdn_url }}"
               target="_blank"
               rel="noopener noreferrer"
               class="btn btn-success me-1 mb-1">
                <i class="bi bi-box-arrow-up-right me-1"></i>
                {% translate "Open" %}
            </a>
        {% endif %}
        {% if has_change_permission %}
            <a href="{{ instance.urls.update }}" class="btn btn-primary me-1 mb-1">{% translate "Edit" %}</a>
        {% endif %}
        {% if has_delete_permission %}
            <button type="button"
                    class="btn btn-danger me-1 mb-1"
                    hx-get="{{ instance.urls.delete }}"
                    hx-target="#deleteInstanceModalContent"
                    data-bs-toggle="modal"
                    data-bs-target="#deleteInstanceModal">{% translate "Delete" %}</button>
        {% endif %}
    </div>
{% endblock page_title_extra %}
{% block page_subtitle %}
    <div class="d-flex flex-wrap align-items-center gap-3 mt-2">
        {% if instance.context.service_definition.service.logo %}
            <img src="{{ instance.context.service_definition.service.logo.url }}"
                 alt="{{ instance.context.service_definition.service.name }}"
                 style="height: 24px;
                        width: auto">
        {% endif %}
        <span class="text-muted">|</span>
        {% if instance.context.service_offering.provider.logo %}
            <img src="{{ instance.context.service_offering.provider.logo.url }}"
                 alt="{{ instance.context.service_offering.provider.name }}"
                 style="height: 24px;
                        width: auto">
        {% endif %}
    </div>
{% endblock page_subtitle %}
{% block content %}
    <section class="section">
        <!-- Row 1: Product Card and Connection Credentials -->
        <div class="row match-height mb-4">
            <div class="col-12 col-md-5">
                {% if compute_plan_assignment or storage_plan %}
                    <div class="card h-100">
                        <div class="card-header">
                            <h4 class="mb-1">{% translate "Product" %}</h4>
                            <p class="text-muted mb-0 small">
                                {{ instance.context.service_definition.service.name }}
                                {% translate "at" %}
                                {{ instance.context.service_offering.provider.name }}
                                ({{ instance.context.control_plane.name }})
                            </p>
                        </div>
                        <div class="card-body">
                            {% if compute_plan_assignment %}
                                <div class="mb-3">
                                    <h6 class="text-muted mb-2">{% translate "Compute" %}</h6>
                                    <div class="mb-1">
                                        {% translate "Plan:" %} <strong>{{ compute_plan_assignment.compute_plan.name }}</strong>
                                    </div>
                                    <div class="text-muted small">
                                        <i class="bi bi-cpu"></i> {{ compute_plan_assignment.compute_plan.cpu_limits }} vCPU
                                        <span class="mx-2">•</span>
                                        <i class="bi bi-memory"></i> {{ compute_plan_assignment.compute_plan.memory_limits }} RAM
                                        <span class="mx-2">•</span>
                                        SLA: {{ compute_plan_assignment.get_sla_display }}
                                    </div>
                                    <div class="mt-1 small">
                                        CHF {{ compute_plan_assignment.price }} / {{ compute_plan_assignment.get_unit_display }}
                                        {% if pricing.compute_monthly %}
                                            <span class="text-muted">(~CHF {{ pricing.compute_monthly }} / {% translate "month" %})</span>
                                        {% endif %}
                                    </div>
                                </div>
                            {% endif %}
                            {% if storage_plan %}
                                <div class="mb-3">
                                    <h6 class="text-muted mb-2">{% translate "Storage" %}</h6>
                                    <div class="text-muted small">
                                        CHF {{ storage_plan.price_per_gib }} / GiB / {% translate "hour" %}
                                        {% if pricing.disk_size_gib %}
                                            <span class="mx-2">•</span>
                                            {{ pricing.disk_size_gib }} GiB {% translate "configured" %}
                                        {% endif %}
                                    </div>
                                    {% if pricing.storage_monthly %}
                                        <div class="mt-1 small">
                                            CHF {{ pricing.storage_hourly }} / {% translate "hour" %}
                                            <span class="text-muted">(~CHF {{ pricing.storage_monthly }} / {% translate "month" %})</span>
                                        </div>
                                    {% endif %}
                                </div>
                            {% endif %}
                            {% if pricing.total_monthly %}
                                <hr class="my-2">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="text-muted">{% translate "Estimated Total" %}</span>
                                    <div class="text-end">
                                        <div>
                                            <strong>~CHF {{ pricing.total_monthly }}</strong> <span class="text-muted small">/ {% translate "month" %}</span>
                                        </div>
                                        <div class="text-muted small">CHF {{ pricing.total_hourly }} / {% translate "hour" %}</div>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                {% endif %}
            </div>
            <div class="col-12 col-md-7">
                {% if instance.connection_credentials %}
                    <div class="card h-100">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="mb-0">{% translate "Connection Credentials" %}</h4>
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary"
                                    id="toggle-credentials-btn"
                                    data-show-text="{% translate "Show All" %}"
                                    data-hide-text="{% translate "Hide All" %}"
                                    onclick="toggleAllCredentials()">
                                <i class="bi bi-eye me-1"></i>
                                <span id="toggle-credentials-text">{% translate "Show All" %}</span>
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered table-fixed mb-0">
                                    <colgroup>
                                        <col style="width: 35%;">
                                        <col style="width: 55%;">
                                        <col style="width: 10%;">
                                    </colgroup>
                                    <thead>
                                        <tr>
                                            <th>{% translate "Name" %}</th>
                                            <th>{% translate "Value" %}</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for key, value in instance.connection_credentials.items %}
                                            {% if "_HOST" not in key and "_URL" not in key %}
                                                <tr>
                                                    <td class="text-truncate">{{ key }}</td>
                                                    <td class="text-truncate">
                                                        {% if key == "error" %}
                                                            <span class="text-danger">{{ value }}</span>
                                                        {% else %}
                                                            <code class="credential-value" data-value="{{ value }}">••••••••••••</code>
                                                        {% endif %}
                                                    </td>
                                                    <td class="text-center">
                                                        {% if key != "error" %}
                                                            <button type="button"
                                                                    class="btn btn-sm btn-link p-0 credential-toggle"
                                                                    onclick="toggleCredential(this)"
                                                                    title="{% translate 'Show/Hide' %}">
                                                                <i class="bi bi-eye"></i>
                                                            </button>
                                                        {% endif %}
                                                    </td>
                                                </tr>
                                            {% endif %}
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                            <div class="text-muted small mt-2">
                                <i class="bi bi-info-circle me-1"></i>
                                {% translate "Click the eye icon to reveal individual credentials, or use 'Show All' to reveal all at once." %}
                            </div>
                        </div>
                    </div>
                {% endif %}
            </div>
        </div>
        <!-- Row 2: Zone Information (left) and Service Configuration (right) -->
        {% if instance.spec and spec_fieldsets or instance.context.control_plane.user_info %}
            <div class="row match-height mb-4">
                <!-- Zone Information (collapsible) -->
                {% if instance.context.control_plane.user_info %}
                    <div class="col-12 col-md-4">
                        <div class="card h-100">
                            <div class="card-header">
                                <h4 class="mb-0">
                                    <a class="text-decoration-none text-dark d-flex align-items-center justify-content-between"
                                       data-bs-toggle="collapse"
                                       href="#zoneInfoCollapse"
                                       role="button"
                                       aria-expanded="false"
                                       aria-controls="zoneInfoCollapse">
                                        {% translate "Zone Documentation" %}
                                        <i class="bi bi-chevron-down ms-2 small"></i>
                                    </a>
                                </h4>
                                <p class="text-muted small mb-0 mt-1">{% translate "Technical details for connecting to this zone" %}</p>
                            </div>
                            <div class="collapse" id="zoneInfoCollapse">
                                <div class="card-body pt-0">
                                    {% include "includes/control_plane_user_info.html" with control_plane=instance.context.control_plane %}
                                </div>
                            </div>
                        </div>
                    </div>
                {% endif %}
                <!-- Service Configuration -->
                {% if instance.spec and spec_fieldsets %}
                    <div class="col-12 {% if instance.context.control_plane.user_info %}col-md-8{% endif %}">
                        <div class="card h-100">
                            <div class="card-header">
                                <h4>{% translate "Service Configuration" %}</h4>
                            </div>
                            <div class="card-body">
                                {% if spec_fieldsets|length > 1 %}
                                    <!-- Multiple fieldsets: use tabs -->
                                    <ul class="nav nav-tabs" role="tablist">
                                        {% for fieldset in spec_fieldsets %}
                                            <li class="nav-item" role="presentation">
                                                <a href="#spec-tab-{{ forloop.counter }}"
                                                   class="nav-link {% if forloop.first %}active{% endif %}"
                                                   data-bs-toggle="tab"
                                                   role="tab">{{ fieldset.title }}</a>
                                            </li>
                                        {% endfor %}
                                    </ul>
                                    <div class="tab-content pt-3">
                                        {% for fieldset in spec_fieldsets %}
                                            <div class="tab-pane fade {% if forloop.first %}show active{% endif %}"
                                                 id="spec-tab-{{ forloop.counter }}"
                                                 role="tabpanel">
                                                <dl class="row mb-0">
                                                    {% for field in fieldset.fields %}
                                                        <dt class="col-sm-4">
                                                            {{ field.label }}
                                                            {% if field.help_text %}
                                                                <i class="bi bi-question-circle text-muted ms-1"
                                                                   data-bs-toggle="popover"
                                                                   data-bs-trigger="hover"
                                                                   data-bs-content="{{ field.help_text }}"></i>
                                                            {% endif %}
                                                        </dt>
                                                        <dd class="col-sm-8">
                                                            {{ field.value|render_tree }}
                                                        </dd>
                                                    {% endfor %}
                                                </dl>
                                                {% for sub_key, sub_fieldset in fieldset.fieldsets.items %}
                                                    <h5 class="mt-3">{{ sub_fieldset.title }}</h5>
                                                    <dl class="row mb-0">
                                                        {% for field in sub_fieldset.fields %}
                                                            <dt class="col-sm-4">{{ field.label }}</dt>
                                                            <dd class="col-sm-8">
                                                                {{ field.value|render_tree }}
                                                            </dd>
                                                        {% endfor %}
                                                    </dl>
                                                {% endfor %}
                                            </div>
                                        {% endfor %}
                                    </div>
                                {% else %}
                                    <!-- Single fieldset: no tabs needed -->
                                    {% for fieldset in spec_fieldsets %}
                                        <dl class="row mb-0">
                                            {% for field in fieldset.fields %}
                                                <dt class="col-sm-4">
                                                    {{ field.label }}
                                                    {% if field.help_text %}
                                                        <i class="bi bi-question-circle text-muted ms-1"
                                                           data-bs-toggle="popover"
                                                           data-bs-trigger="hover"
                                                           data-bs-content="{{ field.help_text }}"></i>
                                                    {% endif %}
                                                </dt>
                                                <dd class="col-sm-8">
                                                    {{ field.value|render_tree }}
                                                </dd>
                                            {% endfor %}
                                        </dl>
                                        {% for sub_key, sub_fieldset in fieldset.fieldsets.items %}
                                            <h5 class="mt-3">{{ sub_fieldset.title }}</h5>
                                            <dl class="row mb-0">
                                                {% for field in sub_fieldset.fields %}
                                                    <dt class="col-sm-4">{{ field.label }}</dt>
                                                    <dd class="col-sm-8">
                                                        {{ field.value|render_tree }}
                                                    </dd>
                                                {% endfor %}
                                            </dl>
                                        {% endfor %}
                                    {% endfor %}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                {% endif %}
            </div>
        {% endif %}
        <!-- Row 3: Expert & Metadata (collapsed) -->
        {% if instance.status_conditions or instance.created_at %}
            <div class="row mb-4">
                <div class="col-12">
                    <div class="accordion" id="expertAccordion">
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="expertHeading">
                                <button class="accordion-button collapsed"
                                        type="button"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#expertCollapse"
                                        aria-expanded="false"
                                        aria-controls="expertCollapse">
                                    <i class="bi bi-gear me-2"></i>
                                    {% translate "Technical Details" %}
                                </button>
                            </h2>
                            <div id="expertCollapse"
                                 class="accordion-collapse collapse"
                                 aria-labelledby="expertHeading"
                                 data-bs-parent="#expertAccordion">
                                <div class="accordion-body">
                                    <div class="row">
                                        <!-- Left column: Status Conditions -->
                                        <div class="col-12 col-md-8">
                                            {% if instance.status_conditions %}
                                                <h5 class="mb-3">{% translate "Status Conditions" %}</h5>
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-sm">
                                                        <thead>
                                                            <tr>
                                                                <th>{% translate "Type" %}</th>
                                                                <th>{% translate "Status" %}</th>
                                                                <th>{% translate "Last Transition" %}</th>
                                                                <th>{% translate "Reason" %}</th>
                                                                <th>{% translate "Message" %}</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            {% for condition in instance.status_conditions %}
                                                                <tr>
                                                                    <td>{{ condition.type }}</td>
                                                                    <td>
                                                                        {% if condition.status == "True" %}
                                                                            <span class="badge text-bg-success">True</span>
                                                                        {% elif condition.status == "False" %}
                                                                            <span class="badge text-bg-danger">False</span>
                                                                        {% else %}
                                                                            <span class="badge text-bg-secondary">{{ condition.status }}</span>
                                                                        {% endif %}
                                                                    </td>
                                                                    <td>{{ condition.lastTransitionTime|localtime_tag }}</td>
                                                                    <td>{{ condition.reason|default:"-" }}</td>
                                                                    <td>{{ condition.message|truncatewords:20|default:"-" }}</td>
                                                                </tr>
                                                            {% endfor %}
                                                        </tbody>
                                                    </table>
                                                </div>
                                            {% endif %}
                                        </div>
                                        <!-- Right column: Metadata -->
                                        <div class="col-12 col-md-4">
                                            <h5 class="mb-3">{% translate "Metadata" %}</h5>
                                            <dl class="row">
                                                <dt class="col-sm-5">{% translate "Created By" %}</dt>
                                                <dd class="col-sm-7">
                                                    {{ instance.created_by|default:"-" }}
                                                </dd>
                                                <dt class="col-sm-5">{% translate "Created At" %}</dt>
                                                <dd class="col-sm-7">
                                                    {{ instance.created_at|localtime_tag }}
                                                </dd>
                                                <dt class="col-sm-5">{% translate "Updated At" %}</dt>
                                                <dd class="col-sm-7">
                                                    {{ instance.updated_at|localtime_tag }}
                                                </dd>
                                            </dl>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        {% endif %}
    </section>
    <!-- Delete Confirmation Modal -->
    <div class="modal fade"
         id="deleteInstanceModal"
         tabindex="-1"
         aria-labelledby="deleteInstanceModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" id="deleteInstanceModalContent">
                {# Content will be loaded here by HTMX #}
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteInstanceModalLabel">{% translate "Confirm Deletion" %}</h5>
                    <button type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">{% translate "Loading..." %}</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% translate "Cancel" %}</button>
                </div>
            </div>
        </div>
    </div>
{% endblock content %}
{% block extra_js %}
    <script src="{% static 'js/local-time.js' %}"></script>
    <script src="{% static 'js/credentials.js' %}"></script>
    <script>
        // Initialize Bootstrap popovers for help text
        document.addEventListener('DOMContentLoaded', function() {
            const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
            [...popoverTriggerList].map(el => new bootstrap.Popover(el));
        });
    </script>
{% endblock extra_js %}
