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

{% block title %}{{ t('forms.title') }}{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📋 {{ t('forms.title') }}</h2>
        <p>{{ t('forms.subtitle') }}</p>
    </div>
    <a href="{{ url_for('admin_forms_new') }}" class="btn btn-primary">{{ t('forms.new_form') }}</a>
</div>

<!-- Status filter -->
<div class="filter-bar">
    <a href="{{ url_for('admin_forms_list', status='all', type=type_filter, lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'all' %}active{% endif %}">{{ t('table.all') }}</a>
    <a href="{{ url_for('admin_forms_list', status='active', type=type_filter, lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'active' %}active{% endif %}">{{ t('forms.status_active') }}</a>
    <a href="{{ url_for('admin_forms_list', status='inactive', type=type_filter, lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'inactive' %}active{% endif %}">{{ t('forms.status_inactive') }}</a>
</div>

<!-- Filters & Search -->
<div class="filter-row">
    <input type="text" id="searchInput" value="{{ search_query or '' }}" placeholder="🔍 {{ t('forms.search_placeholder') }}" autocomplete="off">

    <label>{{ t('table.language') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang='all', sort=sort_by, q=search_query, per_page=per_page) }}" {% if lang_filter == 'all' %}selected{% endif %}>{{ t('table.all_languages') }}</option>
        {% for lang in available_languages %}
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang.code, sort=sort_by, q=search_query, per_page=per_page) }}" {% if lang_filter == lang.code %}selected{% endif %}>{{ lang.name }}</option>
        {% endfor %}
    </select>

    <label class="ml-3">{{ t('forms.form_type') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_forms_list', status=status_filter, type='all', lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}" {% if type_filter == 'all' %}selected{% endif %}>{{ t('forms.all_types') }}</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type='contact', lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}" {% if type_filter == 'contact' %}selected{% endif %}>{{ t('forms.type_contact') }}</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type='subscription', lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}" {% if type_filter == 'subscription' %}selected{% endif %}>{{ t('forms.type_subscription') }}</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type='survey', lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}" {% if type_filter == 'survey' %}selected{% endif %}>{{ t('forms.type_survey') }}</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type='custom', lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}" {% if type_filter == 'custom' %}selected{% endif %}>{{ t('forms.type_custom') }}</option>
    </select>

    <label class="ml-3">{{ t('table.title') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by not in ['title-asc', 'title-desc'] %}selected{% endif %}>—</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang_filter, sort='title-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'title-asc' %}selected{% endif %}>A→Z</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang_filter, sort='title-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'title-desc' %}selected{% endif %}>Z→A</option>
    </select>

    <label class="ml-3">{{ t('table.updated_date') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'updated-desc' %}selected{% endif %}>{{ t('table.newest_first') }}</option>
        <option value="{{ url_for('admin_forms_list', status=status_filter, type=type_filter, lang=lang_filter, sort='updated-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'updated-asc' %}selected{% endif %}>{{ t('table.oldest_first') }}</option>
    </select>
</div>

<div id="forms-content">
{% if forms.items %}
<div class="table-scroll">
<table class="content-table">
    <thead>
        <tr>
            <th>{{ t('table.title') }}</th>
            <th>{{ t('forms.form_type') }}</th>
            <th>{{ t('table.status') }}</th>
            <th>{{ t('table.language') }}</th>
            <th>{{ t('forms.submissions_count') }}</th>
            <th>{{ t('forms.fields') }}</th>
            <th>{{ t('table.updated_date') }}</th>
            <th>{{ t('table.actions') }}</th>
        </tr>
    </thead>
    <tbody>
        {% for form in forms.items %}
        <tr>
            <td>
                <a href="{{ url_for('admin_forms_edit', form_id=form.id) }}" class="page-title-link">{{ form.title }}</a>
                <div class="page-slug">/{{ form.slug }}</div>
            </td>
            <td><span class="form-type-badge">{{ form.form_type }}</span></td>
            <td>
                <span class="badge {{ 'badge-active' if form.is_active else 'badge-inactive' }}">
                    {{ t('forms.status_active') if form.is_active else t('forms.status_inactive') }}
                </span>
            </td>
            <td><span class="lang-badge">{{ form.language|upper }}</span></td>
            <td>
                <strong>{{ form.get_submission_count() }}</strong>
                {% set new_count = form.get_new_submission_count() %}
                {% if new_count > 0 %}
                <span class="badge-new-count">{{ new_count }} {{ t('forms.new_badge') }}</span>
                {% endif %}
            </td>
            <td>{{ form.get_fields()|length }}</td>
            <td class="date-cell">{{ form.updated_at|format_datetime }}</td>
            <td>
                <div class="actions">
                    <a href="{{ url_for('admin_forms_edit', form_id=form.id) }}" class="action-link action-edit">✏️ {{ t('table.edit') }}</a>
                    <a href="{{ url_for('admin_forms_submissions', form_id=form.id) }}" class="action-link action-view">📊 {{ t('forms.submissions_count') }}{% set nc = form.get_new_submission_count() %}{% if nc > 0 %} ({{ nc }}){% endif %}</a>
                    <a href="{{ url_for('admin_forms_translate', form_id=form.id) }}" class="action-link action-translate">🌍 {{ t('table.translate') }}</a>
                    <button type="button" class="action-link action-duplicate" onclick="duplicateItem('form', {{ form.id }}, '{{ form.title|e }}')">📋 {{ t('table.duplicate') }}</button>
                    <form method="POST" action="{{ url_for('admin_forms_delete', form_id=form.id) }}" class="d-inline">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="button" class="action-link action-delete" onclick="checkUsageThenDelete('form', {{ form.id }}, this.closest('form'))">🗑️ {{ t('table.delete') }}</button>
                    </form>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</div>

<!-- Pagination -->
<div class="pagination-footer">
{% if forms.pages > 1 %}
<div class="pagination">
    {% if forms.has_prev %}
        <a href="{{ url_for('admin_forms_list', page=forms.prev_num, status=status_filter, type=type_filter, lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}">{{ t('pagination.prev') }}</a>
    {% endif %}

    {% for p in forms.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == forms.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_forms_list', page=p, status=status_filter, type=type_filter, lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}">{{ p }}</a>
            {% endif %}
        {% else %}
            <span>…</span>
        {% endif %}
    {% endfor %}

    {% if forms.has_next %}
        <a href="{{ url_for('admin_forms_list', page=forms.next_num, status=status_filter, type=type_filter, lang=lang_filter, sort=sort_by, 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 or lang_filter != 'all' or status_filter != 'all' or type_filter != 'all' %}
    <h3>{{ t('forms.no_forms_filtered') }}</h3>
    <a href="{{ url_for('admin_forms_list') }}" class="btn btn-primary">{{ t('forms.clear_filters') }}</a>
    {% else %}
    <h3>{{ t('forms.no_forms') }}</h3>
    <p>{{ t('forms.no_forms_text') }}</p>
    <a href="{{ url_for('admin_forms_new') }}" class="btn btn-primary">{{ t('forms.create_first') }}</a>
    {% endif %}
</div>
{% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
function duplicateItem(contentType, sourceId, title) {
    if (!confirm('{{ t("table.duplicate") }}: "' + title + '"?')) {
        return;
    }

    fetch('/admin/api/duplicate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content_type: contentType, source_id: sourceId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            alert('{{ t("common.error") }}: ' + data.error);
        } else {
            window.location.href = data.edit_url;
        }
    })
    .catch(err => alert('{{ t("common.error") }}: ' + err.message));
}

async function checkUsageThenDelete(assetType, assetId, formEl) {
    try {
        const res = await fetch('/admin/api/check-usage', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: assetType, id: assetId })
        });
        const data = await res.json();
        
        var msg = '{{ t("forms.delete_confirm_generic") }}';
        
        if (data.count > 0) {
            msg = '{{ t("forms.usage_warning") }}\n\n';
            data.usage.forEach(function(u) {
                var typeLabel = u.type.charAt(0).toUpperCase() + u.type.slice(1);
                msg += '• ' + typeLabel + ': ' + u.title + ' (' + u.fields.join(', ') + ')\n';
            });
            msg += '\n{{ t("forms.usage_confirm_delete") }}';
        }
        
        if (confirm(msg)) {
            formEl.submit();
        }
    } catch (err) {
        if (confirm('{{ t("forms.delete_confirm_generic") }}')) {
            formEl.submit();
        }
    }
}

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

    var _csrfToken = '{{ csrf_token() }}';
    var _statusFilter = '{{ status_filter }}';
    var _typeFilter = '{{ type_filter }}';
    var _langFilter = '{{ lang_filter }}';
    var _sortBy = '{{ sort_by }}';
    var _baseUrl = '{{ url_for("admin_forms_list") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        status_active: '{{ t("forms.status_active") }}',
        status_inactive: '{{ t("forms.status_inactive") }}',
        edit: '{{ t("table.edit") }}',
        submissions: '{{ t("forms.submissions_count") }}',
        translate: '{{ t("table.translate") }}',
        duplicate: '{{ t("table.duplicate") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("forms.delete_confirm", title="__TITLE__") }}'.replace(/&#34;/g, '"'),
        new_badge: '{{ t("forms.new_badge") }}',
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}',
        no_forms_filtered: '{{ t("forms.no_forms_filtered") }}',
        clear_filters: '{{ t("forms.clear_filters") }}',
        no_forms: '{{ t("forms.no_forms") }}',
        no_forms_text: '{{ t("forms.no_forms_text") }}',
        create_first: '{{ t("forms.create_first") }}',
        new_url: '{{ url_for("admin_forms_new") }}'
    };

    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 renderContent(data) {
        var container = document.getElementById('forms-content');
        if (!data.items || data.items.length === 0) {
            var hasFilters = input.value.trim() || _statusFilter !== 'all' ||
                            _langFilter !== 'all' || _typeFilter !== 'all';
            container.innerHTML = '<div class="empty-state">' +
                '<div class="empty-state-icon">📋</div>' +
                (hasFilters
                    ? '<h3>' + escapeHtml(_i18n.no_forms_filtered) + '</h3>' +
                      '<a href="' + _baseUrl + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_filters) + '</a>'
                    : '<h3>' + escapeHtml(_i18n.no_forms) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.no_forms_text) + '</p>' +
                      '<a href="' + escapeHtml(_i18n.new_url) + '" class="btn btn-primary">' + escapeHtml(_i18n.create_first) + '</a>'
                ) + '</div>';
            return;
        }

        var rows = data.items.map(function(f) {
            var statusClass = f.is_active ? 'badge-active' : 'badge-inactive';
            var statusLabel = f.is_active ? _i18n.status_active : _i18n.status_inactive;
            var safeTitle = escapeHtml(f.title).replace(/'/g, "\\'");
            var confirmMsg = _i18n.delete_confirm.replace('__TITLE__', safeTitle);
            var newBadge = f.new_submissions > 0
                ? ' <span class="badge-new-count">' + f.new_submissions + ' ' + _i18n.new_badge + '</span>'
                : '';
            var submissionsLink = _i18n.submissions +
                (f.new_submissions > 0 ? ' (' + f.new_submissions + ')' : '');

            return '<tr>' +
                '<td><a href="/admin/forms/' + f.id + '/edit" class="page-title-link">' + escapeHtml(f.title) + '</a>' +
                    '<div class="page-slug">/' + escapeHtml(f.slug) + '</div></td>' +
                '<td><span class="form-type-badge">' + escapeHtml(f.form_type) + '</span></td>' +
                '<td><span class="badge ' + statusClass + '">' + escapeHtml(statusLabel) + '</span></td>' +
                '<td><span class="lang-badge">' + escapeHtml(f.language.toUpperCase()) + '</span></td>' +
                '<td><strong>' + f.submissions_count + '</strong>' + newBadge + '</td>' +
                '<td>' + f.fields_count + '</td>' +
                '<td class="date-cell">' + formatDate(f.updated_at) + '</td>' +
                '<td><div class="actions">' +
                    '<a href="/admin/forms/' + f.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>' +
                    '<a href="/admin/forms/' + f.id + '/submissions" class="action-link action-view">📊 ' + submissionsLink + '</a>' +
                    '<a href="/admin/forms/' + f.id + '/translate" class="action-link action-translate">🌍 ' + _i18n.translate + '</a>' +
                    '<button type="button" class="action-link action-duplicate" onclick="duplicateItem(\'form\',' + f.id + ',\'' + safeTitle + '\')">📋 ' + _i18n.duplicate + '</button>' +
                    '<form method="POST" action="/admin/forms/' + f.id + '/delete" class="d-inline">' +
                        '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                        '<button type="button" class="action-link action-delete" onclick="checkUsageThenDelete(\'form\',' + f.id + ',this.closest(\'form\'))">🗑️ ' + _i18n.delete_action + '</button>' +
                    '</form>' +
                '</div></td></tr>';
        }).join('');

        var html = '<div class="table-scroll"><table class="content-table"><thead><tr>' +
            '<th>{{ t("table.title") }}</th><th>{{ t("forms.form_type") }}</th>' +
            '<th>{{ t("table.status") }}</th><th>{{ t("table.language") }}</th>' +
            '<th>{{ t("forms.submissions_count") }}</th><th>{{ t("forms.fields") }}</th>' +
            '<th>{{ t("table.updated_date") }}</th><th>{{ t("table.actions") }}</th>' +
            '</tr></thead><tbody>' + rows + '</tbody></table></div>';

        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();
        params.set('status', _statusFilter);
        params.set('type', _typeFilter);
        params.set('lang', _langFilter);
        params.set('sort', _sortBy);
        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 %}
