{% extends 'base.html' %}

{% block title %}Теги{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <!-- Заголовок и быстрое создание -->
            <div class="d-flex align-items-center gap-3 mb-3">
                <h5 class="mb-0"><i class="bi bi-tags text-primary"></i> Теги</h5>
                <div class="input-group input-group-sm flex-grow-1" style="max-width: 300px;">
                    <input type="text" id="quick-tag-input" class="form-control" placeholder="Новый тег..." autocomplete="off">
                    <button class="btn btn-primary" id="quick-tag-btn" type="button"><i class="bi bi-plus"></i></button>
                </div>
            </div>
            <div id="quick-tag-message"></div>

            <!-- Поиск и фильтр в одну строку -->
            <form method="get" class="d-flex gap-2 mb-3">
                <input type="text" class="form-control form-control-sm" name="search" value="{{ search_query }}" placeholder="Поиск...">
                <select class="form-select form-select-sm" name="is_active" style="width: auto;" onchange="this.form.submit()">
                    <option value="">Все</option>
                    <option value="1" {% if is_active_filter == '1' %}selected{% endif %}>Активные</option>
                    <option value="0" {% if is_active_filter == '0' %}selected{% endif %}>Неактивные</option>
                </select>
                <button type="submit" class="btn btn-outline-secondary btn-sm"><i class="bi bi-search"></i></button>
            </form>

            <!-- Список тегов -->
            {% if tags %}
            <div class="list-group list-group-flush">
                {% for tag in tags %}
                <div class="list-group-item d-flex align-items-center py-2 px-3">
                    <div class="form-check form-switch me-3 mb-0">
                        <input class="form-check-input tag-status-switch" type="checkbox" data-tag-id="{{ tag.pk }}" {% if tag.is_active %}checked{% endif %}>
                    </div>
                    <div class="flex-grow-1">
                        <a href="{% url 'products:tag-detail' tag.pk %}" class="text-decoration-none fw-medium">{{ tag.name }}</a>
                        <small class="text-muted ms-2">{{ tag.slug }}</small>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge bg-secondary" title="Товаров">{{ tag.products_count }}</span>
                        <span class="badge bg-secondary" title="Комплектов">{{ tag.kits_count }}</span>
                        <div class="btn-group btn-group-sm">
                            <a href="{% url 'products:tag-update' tag.pk %}" class="btn btn-outline-secondary btn-sm py-0 px-1" title="Изменить"><i class="bi bi-pencil"></i></a>
                            <a href="{% url 'products:tag-delete' tag.pk %}" class="btn btn-outline-danger btn-sm py-0 px-1" title="Удалить"><i class="bi bi-trash"></i></a>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- Пагинация -->
            {% if is_paginated %}
            <nav class="mt-3">
                <ul class="pagination pagination-sm justify-content-center mb-0">
                    {% if page_obj.has_previous %}
                    <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if is_active_filter %}&is_active={{ is_active_filter }}{% endif %}">&laquo;</a></li>
                    {% endif %}
                    <li class="page-item active"><span class="page-link">{{ page_obj.number }}/{{ page_obj.paginator.num_pages }}</span></li>
                    {% if page_obj.has_next %}
                    <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if is_active_filter %}&is_active={{ is_active_filter }}{% endif %}">&raquo;</a></li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}

            {% else %}
            <div class="text-center text-muted py-4">
                <i class="bi bi-tag fs-1 opacity-25"></i>
                <p class="mb-0 mt-2">Тегов пока нет</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('quick-tag-input');
    const btn = document.getElementById('quick-tag-btn');
    const messageDiv = document.getElementById('quick-tag-message');

    function createTag() {
        const name = input.value.trim();
        if (!name) return;

        btn.disabled = true;
        input.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

        fetch('{% url "products:api-tag-create" %}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' },
            body: JSON.stringify({name: name})
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                showMessage('Тег создан', 'success');
                setTimeout(() => window.location.reload(), 500);
            } else {
                showMessage(data.error, 'danger');
                resetBtn();
            }
        })
        .catch(() => { showMessage('Ошибка сети', 'danger'); resetBtn(); });
    }

    function resetBtn() {
        btn.disabled = false;
        input.disabled = false;
        btn.innerHTML = '<i class="bi bi-plus"></i>';
        input.focus();
    }

    function showMessage(text, type) {
        messageDiv.innerHTML = `<div class="alert alert-${type} py-1 px-2 small mb-2">${text}</div>`;
        setTimeout(() => messageDiv.innerHTML = '', 3000);
    }

    btn.addEventListener('click', createTag);
    input.addEventListener('keypress', e => { if (e.key === 'Enter') { e.preventDefault(); createTag(); } });

    // Toggle статуса
    document.querySelectorAll('.tag-status-switch').forEach(toggle => {
        toggle.addEventListener('click', async function(e) {
            e.preventDefault();
            const tagId = this.dataset.tagId;
            try {
                const response = await fetch(`/products/api/tags/${tagId}/toggle/`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }
                });
                const data = await response.json();
                if (data.success) this.checked = data.is_active;
            } catch (error) {}
        });
    });
});
</script>

{% endblock %}
