{% extends "_base.html" %}

{% block title %}Record Details - {{ doc.get(unique_key_field, '-') }}{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
{% endblock %}

{% block content %}

    <div class="container mx-auto px-4 pt-8">
        <div class="card bg-base-100 shadow-xl mb-8">
            <div class="card-body">
                <h1 class="card-title">Details für Record: <span class="badge badge-primary">{{ doc.get(unique_key_field, '-') }}</span></h1>
                <div class="card-actions justify-end">
                    <button id="toggle-json" class="btn btn-ghost">Rohes JSON umschalten</button>
                </div>
            </div>
        </div>

        <div id="json-container" style="display: none;" class="mb-8">
            <div class="mockup-code">
                <pre><code class="json">{{ doc | tojson(indent=4) }}</code></pre>
            </div>
        </div>

        {% if error %}
            <div role="alert" class="alert alert-error mb-8">
                <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                <span>Fehler: {{ error }}</span>
            </div>
        {% else %}
            <div class="overflow-x-auto bg-base-100 rounded-box shadow-xl mb-8" style="max-height: 70vh;">
                <table class="table table-zebra table-pin-rows">
                    <thead>
                        <tr>
                            <th>Feldname</th>
                            <th>Datentyp</th>
                            <th>Multivalued</th>
                            <th>Stored</th>
                            <th>Wert</th>
                            <th>Aktion</th>
                        </tr>
                    </thead>
                    <tbody id="record-table-body">
                        {% if display_fields %}
                            {% for field_data in display_fields %}
                                {% set field = field_data.definition %}
                                {% include '_record_row.html' %}
                            {% endfor %}
                        {% else %}
                            <!-- Fallback für alte Implementierung -->
                            {% for field in schema_fields %}
                                {% include '_record_row.html' %}
                            {% endfor %}
                        {% endif %}
                    </tbody>
                </table>
            </div>
        {% endif %}

        <div class="card bg-base-100 shadow-xl">
            <div class="card-body">
                <h3 class="card-title">Neues Feld hinzufügen</h3>
                <p>Fügen Sie dem Dokument ein neues Feld hinzu. Dies ist besonders nützlich für dynamische Felder.</p>
                <form action="{{ url_for('record.add_field', doc_id=doc[unique_key_field]) }}" method="post" class="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                    <div class="form-control">
                        <label class="label" for="field_name"><span class="label-text">Feldname</span></label>
                        <input type="text" id="field_name" name="field_name" placeholder="z.B. kommentar_str" required class="input input-bordered w-full">
                    </div>
                    <div class="form-control">
                        <label class="label" for="field_value"><span class="label-text">Wert</span></label>
                        <input type="text" id="field_value" name="field_value" placeholder="Wert des Feldes" required class="input input-bordered w-full">
                    </div>
                    <div class="form-control">
                        <button type="submit" class="btn btn-primary w-full">Hinzufügen</button>
                    </div>
                </form>
                {% if schema.dynamic_fields %}
                    <div class="divider">Verfügbare dynamische Feldmuster</div>
                    <div class="flex flex-wrap gap-2">
                        {% for df in schema.dynamic_fields %}
                            <div class="badge badge-outline">{{ df.name }}</div>
                        {% endfor %}
                    </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- HTMX Modal Container -->
    <div id="modal-container"></div>

    <!-- DaisyUI Modal für Edit-Form -->
    <dialog id="edit-modal" class="modal">
        <div class="modal-box w-11/12 max-w-2xl">
            <div id="modal-content">
                <!-- HTMX lädt hier den Inhalt -->
            </div>
        </div>
        <form method="dialog" class="modal-backdrop">
            <button>close</button>
        </form>
    </dialog>

    <script>
        // Script for JSON viewer
        document.getElementById('toggle-json').addEventListener('click', function() {
            var container = document.getElementById('json-container');
            if (container.style.display === 'none') {
                container.style.display = 'block';
                hljs.highlightAll();
            } else {
                container.style.display = 'none';
            }
        });

        // HTMX Modal Logic für Edit-Forms
        document.body.addEventListener('htmx:afterSwap', function(evt) {
            // Wenn Inhalt in modal-content geladen wurde, ist das Modal bereits offen
            if (evt.detail.target.id === 'modal-content' && evt.detail.xhr.status === 200) {
                // Modal ist bereits durch onclick geöffnet, nichts zu tun
                console.log('Edit-Form geladen');
            }
        });

        function closeModal() {
            var modal = document.getElementById('edit-modal');
            if (modal) {
                modal.close();
                // Inhalt leeren für nächstes Mal
                document.getElementById('modal-content').innerHTML = '';
            }
        }

        // Globale closeModal Funktion für HTMX
        window.closeModal = closeModal;

        // Schließe Modal nach erfolgreichem Update
        document.body.addEventListener('htmx:afterRequest', function(event) {
            console.log('HTMX afterRequest:', event.detail);

            // Prüfe verschiedene Bedingungen für Modal-Schließung
            const isModalContent = event.detail.target.id === 'modal-content';
            const isSuccessful = event.detail.xhr.status === 200;
            const isPostRequest = event.detail.requestConfig && event.detail.requestConfig.verb === 'post';
            const isUpdateField = event.detail.pathInfo && event.detail.pathInfo.requestPath.includes('/update-field');

            console.log('Modal conditions:', { isModalContent, isSuccessful, isPostRequest, isUpdateField });

            if (isModalContent && isSuccessful && isPostRequest) {
                console.log('Schließe Modal nach erfolgreichem Update');
                closeModal();
                // Zeige Toast-Benachrichtigung
                if (window.showToast) {
                    window.showToast('Feld erfolgreich aktualisiert!', 'success');
                }
            }
        });

        // Alternative: Schließe Modal bei erfolgreichem Swap
        document.body.addEventListener('htmx:afterSwap', function(event) {
            // Wenn eine Tabellenzeile ersetzt wurde (Update erfolgreich)
            if (event.detail.target.id && event.detail.target.id.startsWith('row-')) {
                console.log('Tabellenzeile aktualisiert, schließe Modal');
                closeModal();
                if (window.showToast) {
                    window.showToast('Feld erfolgreich aktualisiert!', 'success');
                }
            }
        });
    </script>
{% endblock %}
