{% extends 'admin/base.html' %}

{% block title %}{{ t('submissions.title') }} — {{ form.title }}{% endblock %}

{% block content %}
<div class="container-xl">
    <div class="page-header--with-action">
        <div class="page-header__content">
            <h2>📊 {{ t('submissions.title') }} — {{ form.title }}</h2>
        </div>
        <div class="btn-group">
            <a href="{{ url_for('admin_forms_edit', form_id=form.id) }}" class="btn btn-secondary">✏️ {{ t('common.edit') }}</a>
            <a href="{{ url_for('admin_forms_export', form_id=form.id, format='csv') }}" class="btn btn-secondary">📥 {{ t('submissions.export_csv') }}</a>
            <a href="{{ url_for('admin_forms_export', form_id=form.id, format='excel') }}" class="btn btn-secondary">📊 {{ t('submissions.export_excel') }}</a>
            <a href="{{ admin_back_url('admin_forms_list') }}" class="btn btn-primary">← {{ t('common.back') }}</a>
        </div>
    </div>

    <!-- Status filters & Search -->
    <div class="filter-bar">
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, per_page=per_page) }}" class="filter-link {{ 'active' if not status_filter }}">{{ t('submissions.all') }} ({{ form.get_submission_count() }})</a>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, status='new', per_page=per_page) }}" class="filter-link {{ 'active' if status_filter == 'new' }}">{{ t('submissions.new') }} ({{ form.submissions.filter_by(status='new').count() }})</a>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, status='read', per_page=per_page) }}" class="filter-link {{ 'active' if status_filter == 'read' }}">{{ t('submissions.read') }}</a>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, status='archived', per_page=per_page) }}" class="filter-link {{ 'active' if status_filter == 'archived' }}">{{ t('submissions.archived') }}</a>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, status='spam', per_page=per_page) }}" class="filter-link {{ 'active' if status_filter == 'spam' }}">{{ t('submissions.spam') }}</a>
        <input type="text" id="searchInput" value="{{ search_query or '' }}" placeholder="🔍 {{ t('submissions.search_placeholder') }}" autocomplete="off" class="input-medium" style="margin-inline-start:auto;">
    </div>

    <div id="submissions-content">
    {% if submissions %}
    {% set fields = form.get_fields() %}

    <!-- Bulk actions bar -->
    <div class="bulk-actions d-none" id="bulkActions">
        <span id="selectedCount">0</span> {{ t('table.selected') }}
        <button type="button" class="btn btn-danger btn-sm" onclick="bulkDelete()">🗑️ {{ t('submissions.delete_selected') }}</button>
        <button type="button" class="btn btn-secondary btn-sm" onclick="clearSelection()">{{ t('submissions.clear_selection') }}</button>
    </div>

    <form id="bulkDeleteForm" method="POST" action="{{ url_for('admin_forms_submissions_bulk_delete', form_id=form.id) }}">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="status" value="{{ status_filter }}">
        <input type="hidden" name="q" value="{{ search_query }}">

        <div class="table-scroll">
        <table class="content-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all" onchange="toggleAll(this.checked)" title="{{ t('submissions.select_all') }}"></th>
                    <th>#</th>
                    <th>{{ t('submissions.date') }}</th>
                    <th>{{ t('submissions.status') }}</th>
                    {% set form_settings = form.get_settings() %}
                    {% if form_settings.double_opt_in %}
                    <th>{{ t('submissions.email_status') }}</th>
                    {% endif %}
                    {% for field in fields[:5] %}
                    <th>{{ field.label }}</th>
                    {% endfor %}
                    <th>{{ t('table.actions') }}</th>
                </tr>
            </thead>
            <tbody>
                {% for sub in submissions %}
                {% set data = sub.get_data() %}
                <tr>
                    <td><input type="checkbox" name="selected_ids" value="{{ sub.id }}" class="sub-checkbox" onchange="updateBulkBar()"></td>
                    <td>{{ sub.id }}</td>
                    <td class="date-cell">{{ sub.created_at|format_datetime }}</td>
                    <td><span class="sub-status sub-status--{{ sub.status }}">{{ t('submissions.' + sub.status) }}</span></td>
                    {% if form_settings.double_opt_in %}
                    <td>
                        {% if sub.email_confirmed == true %}
                            <span class="badge-confirmed">✅ {{ t('submissions.email_confirmed') }}</span>
                        {% elif sub.email_confirmed == false %}
                            <span class="badge-pending">⏳ {{ t('submissions.email_pending') }}</span>
                        {% else %}
                            <span class="text-muted">—</span>
                        {% endif %}
                    </td>
                    {% endif %}
                    {% for field in fields[:5] %}
                    <td title="{{ data.get(field.name, '')|string }}" class="td-truncate">
                        {% set val = data.get(field.name, '') %}
                        {% if val is iterable and val is not string %}{{ val|join(', ')|truncate(40) }}{% else %}{{ val|string|truncate(40) }}{% endif %}
                    </td>
                    {% endfor %}
                    <td>
                        <div class="actions">
                            <a href="{{ url_for('admin_forms_submission_detail', form_id=form.id, sub_id=sub.id) }}" class="action-link action-view">{{ t('table.view') }}</a>
                            <button type="button" class="action-link action-delete" onclick="deleteSubmission({{ sub.id }})">{{ t('submissions.delete') }}</button>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
    </form>

    <div class="pagination-footer">
    {% if pagination.pages > 1 %}
    <div class="pagination">
        {% if pagination.has_prev %}
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, page=pagination.prev_num, status=status_filter, q=search_query, per_page=per_page) }}">{{ t('pagination.prev') }}</a>
        {% endif %}

        {% for p in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
            {% if p %}
                {% if p == pagination.page %}
                    <span class="current">{{ p }}</span>
                {% else %}
                    <a href="{{ url_for('admin_forms_submissions', form_id=form.id, page=p, status=status_filter, q=search_query, per_page=per_page) }}">{{ p }}</a>
                {% endif %}
            {% else %}
                <span>…</span>
            {% endif %}
        {% endfor %}

        {% if pagination.has_next %}
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, page=pagination.next_num, status=status_filter, q=search_query, per_page=per_page) }}">{{ t('pagination.next') }}</a>
        {% endif %}
    </div>
    {% endif %}
    <div class="per-page-selector">
        <span>{{ t('pagination.per_page') }}</span>
        <select onchange="var u=new URLSearchParams(location.search);u.set('per_page',this.value);u.delete('page');location.search=u">
            {% for pp in [20, 50, 100] %}
            <option value="{{ pp }}" {% if per_page == pp %}selected{% endif %}>{{ pp }}</option>
            {% endfor %}
        </select>
        <span>{{ t('pagination.per_page_suffix') }}</span>
    </div>
    </div>

    {% else %}
    <div class="empty-state">
        <div class="empty-state-icon">📭</div>
        {% if search_query %}
        <h3>{{ t('submissions.no_results') }}</h3>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id, status=status_filter, per_page=per_page) }}" class="btn btn-primary">{{ t('submissions.clear_search') }}</a>
        {% else %}
        <h3>{{ t('submissions.no_submissions') }}</h3>
        <p>{{ t('submissions.no_submissions_text') }}</p>
        {% endif %}
    </div>
    {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function toggleAll(checked) {
    document.querySelectorAll('.sub-checkbox').forEach(function(cb) {
        cb.checked = checked;
    });
    updateBulkBar();
}

function updateBulkBar() {
    var checked = document.querySelectorAll('.sub-checkbox:checked');
    var bar = document.getElementById('bulkActions');
    var count = document.getElementById('selectedCount');
    var selectAll = document.getElementById('select-all');

    count.textContent = checked.length;
    if (checked.length > 0) {
        bar.classList.remove('d-none');
    } else {
        bar.classList.add('d-none');
    }

    var total = document.querySelectorAll('.sub-checkbox');
    selectAll.checked = total.length > 0 && checked.length === total.length;
}

function bulkDelete() {
    var checked = document.querySelectorAll('.sub-checkbox:checked');
    if (checked.length === 0) return;

    AdminDialog.confirm('{{ t("submissions.bulk_delete_confirm") }}'.replace('{count}', checked.length), { danger: true }).then(function(ok) {
        if (ok) document.getElementById('bulkDeleteForm').submit();
    });
}

function clearSelection() {
    document.querySelectorAll('.sub-checkbox').forEach(function(cb) {
        cb.checked = false;
    });
    document.getElementById('select-all').checked = false;
    updateBulkBar();
}

// ── Single submission delete (via fetch, avoids nested form issue) ──
function deleteSubmission(subId) {
    AdminDialog.confirm('{{ t("submissions.delete_confirm") }}', { danger: true }).then(function(ok) {
    if (!ok) return;
    fetch('/admin/forms/submissions/' + subId + '/delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'csrf_token=' + encodeURIComponent('{{ csrf_token() }}')
    })
    .then(function(r) {
        if (r.ok || r.redirected) {
            location.reload();
        } else {
            AdminDialog.alert('{{ t("common.error") }}');
        }
    })
    .catch(function() {
        AdminDialog.alert('{{ t("common.error") }}');
    });
    });
}

// Live search — updates table without page reload
(function() {
    var input = document.getElementById('searchInput');
    if (!input) return;

    var _csrfToken = '{{ csrf_token() }}';
    var _formId = {{ form.id }};
    var _statusFilter = '{{ status_filter }}';
    var _baseUrl = '{{ url_for("admin_forms_submissions", form_id=form.id) }}';
    var _bulkDeleteUrl = '{{ url_for("admin_forms_submissions_bulk_delete", form_id=form.id) }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        selected: '{{ t("table.selected") }}',
        delete_selected: '{{ t("submissions.delete_selected") }}',
        clear_selection: '{{ t("submissions.clear_selection") }}',
        select_all: '{{ t("submissions.select_all") }}',
        date: '{{ t("submissions.date") }}',
        status_label: '{{ t("submissions.status") }}',
        email_status: '{{ t("submissions.email_status") }}',
        email_confirmed: '{{ t("submissions.email_confirmed") }}',
        email_pending: '{{ t("submissions.email_pending") }}',
        view: '{{ t("table.view") }}',
        delete_action: '{{ t("submissions.delete") }}',
        delete_confirm: '{{ t("submissions.delete_confirm") }}',
        bulk_delete_confirm: '{{ t("submissions.bulk_delete_confirm") }}',
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}',
        no_results: '{{ t("submissions.no_results") }}',
        clear_search: '{{ t("submissions.clear_search") }}',
        no_submissions: '{{ t("submissions.no_submissions") }}',
        no_submissions_text: '{{ t("submissions.no_submissions_text") }}',
        new: '{{ t("submissions.new") }}',
        read: '{{ t("submissions.read") }}',
        archived: '{{ t("submissions.archived") }}',
        spam: '{{ t("submissions.spam") }}'
    };

    var _statusLabels = {
        'new': _i18n.new,
        'read': _i18n.read,
        'archived': _i18n.archived,
        'spam': _i18n.spam
    };

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str || ''));
        return div.innerHTML;
    }

    function formatDate(iso) {
        if (!iso) return '—';
        var d = new Date(iso);
        return d.toLocaleDateString('en-CA') + ' ' +
               d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
    }

    function truncate(str, len) {
        str = String(str || '');
        return str.length > len ? str.substring(0, len) + '…' : str;
    }

    function renderContent(data) {
        var container = document.getElementById('submissions-content');
        if (!data.items || data.items.length === 0) {
            var hasSearch = input.value.trim();
            container.innerHTML = '<div class="empty-state">' +
                '<div class="empty-state-icon">📭</div>' +
                (hasSearch
                    ? '<h3>' + escapeHtml(_i18n.no_results) + '</h3>' +
                      '<a href="' + _baseUrl + ((_statusFilter) ? '?status=' + _statusFilter : '') + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_search) + '</a>'
                    : '<h3>' + escapeHtml(_i18n.no_submissions) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.no_submissions_text) + '</p>'
                ) + '</div>';
            return;
        }

        var fields = data.fields || [];
        var hasDoubleOptIn = data.double_opt_in;

        /* Bulk actions bar */
        var html = '<div class="bulk-actions d-none" id="bulkActions">' +
            '<span id="selectedCount">0</span> ' + escapeHtml(_i18n.selected) +
            ' <button type="button" class="btn btn-danger btn-sm" onclick="bulkDelete()">🗑️ ' + escapeHtml(_i18n.delete_selected) + '</button>' +
            ' <button type="button" class="btn btn-secondary btn-sm" onclick="clearSelection()">' + escapeHtml(_i18n.clear_selection) + '</button></div>';

        /* Bulk delete form wrapping table */
        html += '<form id="bulkDeleteForm" method="POST" action="' + _bulkDeleteUrl + '">' +
            '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
            '<input type="hidden" name="status" value="' + escapeHtml(_statusFilter) + '">' +
            '<input type="hidden" name="q" value="' + escapeHtml(input.value.trim()) + '">';

        /* Table header */
        html += '<div class="table-scroll"><table class="content-table"><thead><tr>' +
            '<th><input type="checkbox" id="select-all" onchange="toggleAll(this.checked)" title="' + escapeHtml(_i18n.select_all) + '"></th>' +
            '<th>#</th><th>' + escapeHtml(_i18n.date) + '</th><th>' + escapeHtml(_i18n.status_label) + '</th>';
        if (hasDoubleOptIn) {
            html += '<th>' + escapeHtml(_i18n.email_status) + '</th>';
        }
        fields.forEach(function(f) { html += '<th>' + escapeHtml(f.label) + '</th>'; });
        html += '<th>{{ t("table.actions") }}</th></tr></thead><tbody>';

        /* Rows */
        data.items.forEach(function(sub) {
            var statusLabel = _statusLabels[sub.status] || sub.status;
            html += '<tr>' +
                '<td><input type="checkbox" name="selected_ids" value="' + sub.id + '" class="sub-checkbox" onchange="updateBulkBar()"></td>' +
                '<td>' + sub.id + '</td>' +
                '<td class="date-cell">' + formatDate(sub.created_at) + '</td>' +
                '<td><span class="sub-status sub-status--' + escapeHtml(sub.status) + '">' + escapeHtml(statusLabel) + '</span></td>';

            if (hasDoubleOptIn) {
                if (sub.email_confirmed === true) {
                    html += '<td><span class="badge-confirmed">✅ ' + escapeHtml(_i18n.email_confirmed) + '</span></td>';
                } else if (sub.email_confirmed === false) {
                    html += '<td><span class="badge-pending">⏳ ' + escapeHtml(_i18n.email_pending) + '</span></td>';
                } else {
                    html += '<td><span class="text-muted">—</span></td>';
                }
            }

            fields.forEach(function(f) {
                var val = sub.data[f.name];
                if (Array.isArray(val)) val = val.join(', ');
                val = truncate(val, 40);
                html += '<td class="td-truncate" title="' + escapeHtml(val) + '">' + escapeHtml(val) + '</td>';
            });

            html += '<td><div class="actions">' +
                '<a href="/admin/forms/' + _formId + '/submissions/' + sub.id + '" class="action-link action-view">' + _i18n.view + '</a>' +
                '<button type="button" class="action-link action-delete" onclick="deleteSubmission(' + sub.id + ')">' + _i18n.delete_action + '</button>' +
                '</div></td></tr>';
        });

        html += '</tbody></table></div></form>';

        /* Pagination */
        html += '<div class="pagination-footer">';
        if (data.pages > 1) {
            html += '<div class="pagination">';
            if (data.has_prev) {
                html += '<a href="#" onclick="window._liveSearch(' + data.prev_num + ');return false">' + _i18n.prev + '</a>';
            }
            var pageNums = [], i;
            for (i = 1; i <= data.pages; i++) {
                if (i === 1 || i === data.pages || (i >= data.page - 2 && i <= data.page + 2)) {
                    pageNums.push(i);
                } else if (pageNums[pageNums.length - 1] !== null) {
                    pageNums.push(null);
                }
            }
            pageNums.forEach(function(p) {
                if (p === null) { html += '<span>…</span>'; }
                else if (p === data.page) { html += '<span class="current">' + p + '</span>'; }
                else { html += '<a href="#" onclick="window._liveSearch(' + p + ');return false">' + p + '</a>'; }
            });
            if (data.has_next) {
                html += '<a href="#" onclick="window._liveSearch(' + data.next_num + ');return false">' + _i18n.next + '</a>';
            }
            html += '</div>';
        }
        html += '<div class="per-page-selector">' +
            '<span>' + _i18n.per_page_label + '</span>' +
            '<select onchange="var u=new URLSearchParams(location.search);u.set(\'per_page\',this.value);u.delete(\'page\');location.search=u">' +
            [20,50,100].map(function(pp) { return '<option value="' + pp + '"' + (pp === _perPage ? ' selected' : '') + '>' + pp + '</option>'; }).join('') +
            '</select>' +
            '<span>' + _i18n.per_page_suffix + '</span></div>';
        html += '</div>';  /* close pagination-footer */

        container.innerHTML = html;
    }

    window._liveSearch = function(page) {
        var q = input.value.trim();
        var params = new URLSearchParams();
        if (_statusFilter) params.set('status', _statusFilter);
        params.set('format', 'json');
        if (_perPage && _perPage !== 20) params.set('per_page', _perPage);
        if (q) params.set('q', q);
        if (page && page > 1) params.set('page', page);

        fetch(_baseUrl + '?' + params.toString())
            .then(function(r) { return r.json(); })
            .then(function(data) {
                renderContent(data);
                var urlParams = new URLSearchParams(window.location.search);
                if (q) { urlParams.set('q', q); } else { urlParams.delete('q'); }
                if (page && page > 1) { urlParams.set('page', page); } else { urlParams.delete('page'); }
                urlParams.delete('format');
                history.replaceState(null, '', window.location.pathname +
                    (urlParams.toString() ? '?' + urlParams.toString() : ''));
            })
            .catch(function(err) { console.error('Search error:', err); });
    };

    input.addEventListener('input', function() {
        clearTimeout(_debounceTimer);
        _debounceTimer = setTimeout(function() { window._liveSearch(1); }, 300);
    });
})();
</script>
{% endblock %}
