{% extends 'base.html' %}
{% load quality_tags %}

{% block title %}Товары и комплекты{% endblock %}

{% block content %}
{% csrf_token %}
<div class="container-fluid mt-4">
    <h2 class="mb-4">
        <i class="bi bi-box-seam"></i> Товары и комплекты
    </h2>

    <!-- Панель фильтрации и действий -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
                <h5 class="card-title mb-0 me-3">
                    <i class="bi bi-funnel-fill"></i> Фильтры
                </h5>
                <div class="btn-toolbar" role="toolbar">
                    {% if action_buttons %}
                        {% for button in action_buttons %}
                        <a href="{{ button.url }}" class="btn {{ button.class|default:'btn-primary' }} btn-sm me-2 mb-2 mb-md-0">
                            {% if button.icon %}<i class="bi bi-{{ button.icon }}"></i>{% endif %}
                            {{ button.text }}
                        </a>
                        {% endfor %}
                    {% endif %}
                    
                    <!-- Кнопка импорта товаров -->
                    <a href="{% url 'products:product-import' %}" class="btn btn-outline-primary btn-sm me-2 mb-2 mb-md-0">
                        <i class="bi bi-upload"></i> Импорт
                    </a>
                </div>
            </div>

            <hr class="my-3">

            <form method="get" id="filterForm">
                <div class="row g-3">
                    <!-- Поиск -->
                    <div class="col-12 col-md-4">
                        <label for="search" class="form-label"><i class="bi bi-search"></i> Поиск</label>
                        <input type="text" class="form-control" id="search" name="search" 
                               placeholder="Название, артикул, описание..." 
                               value="{{ filters.current.search|default:'' }}">
                    </div>

                    <!-- Тип -->
                    <div class="col-12 col-md-2">
                        <label for="type" class="form-label"><i class="bi bi-box"></i> Тип</label>
                        <select class="form-select" id="type" name="type">
                            <option value="all" {% if filters.current.type == 'all' %}selected{% endif %}>Все</option>
                            <option value="products" {% if filters.current.type == 'products' %}selected{% endif %}>Только товары</option>
                            <option value="kits" {% if filters.current.type == 'kits' %}selected{% endif %}>Только комплекты</option>
                        </select>
                    </div>

                    <!-- Категория -->
                    <div class="col-12 col-md-3">
                        <label for="category" class="form-label"><i class="bi bi-bookmark"></i> Категория</label>
                        <select class="form-select" id="category" name="category">
                            <option value="">Все категории</option>
                            {% for category in filters.categories %}
                            <option value="{{ category.id }}" {% if filters.current.category == category.id|stringformat:"s" %}selected{% endif %}>
                                {{ category.name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- Статус -->
                    <div class="col-12 col-md-3">
                        <label for="status" class="form-label"><i class="bi bi-toggle-on"></i> Статус</label>
                        <select class="form-select" id="status" name="status">
                            <option value="">Все статусы</option>
                            {% for status_value, status_name in item_statuses %}
                            <option value="{{ status_value }}" {% if filters.current.status == status_value %}selected{% endif %}>
                                {{ status_name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>

                <div class="row g-3 mt-2">
                    <!-- В наличии (только для товаров) -->
                    <div class="col-12 col-md-3">
                        <label for="in_stock" class="form-label"><i class="bi bi-check-circle"></i> В наличии</label>
                        <select class="form-select" id="in_stock" name="in_stock">
                            <option value="">Все</option>
                            <option value="1" {% if filters.current.in_stock == '1' %}selected{% endif %}>Да</option>
                            <option value="0" {% if filters.current.in_stock == '0' %}selected{% endif %}>Нет</option>
                        </select>
                    </div>

                    <!-- Теги -->
                    <div class="col-12 col-md-3">
                        <label for="tags" class="form-label"><i class="bi bi-tags"></i> Теги</label>
                        <select class="form-select" id="tags" name="tags" multiple size="1">
                            {% for tag in filters.tags %}
                            <option value="{{ tag.id }}" {% if tag.id in filters.current.tags %}selected{% endif %}>
                                {{ tag.name }}
                            </option>
                            {% endfor %}
                        </select>
                        {% if filters.current.tags %}
                        <small class="text-muted">Выбрано: {{ filters.current.tags|length }}</small>
                        {% endif %}
                    </div>

                    <!-- Показывать по -->
                    <div class="col-12 col-md-2">
                        <label for="per_page" class="form-label"><i class="bi bi-list-ol"></i> Показывать по:</label>
                        <select class="form-select" id="per_page" name="per_page" onchange="this.form.submit()">
                            <option value="20" {% if filters.current.per_page == '20' %}selected{% endif %}>20</option>
                            <option value="50" {% if filters.current.per_page == '50' %}selected{% endif %}>50</option>
                            <option value="100" {% if filters.current.per_page == '100' %}selected{% endif %}>100</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label d-none d-md-block">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-check-circle"></i> Применить
                            </button>
                            <a href="{% url 'products:products-list' %}" class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle"></i> Сбросить
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    {% if items %}
    <!-- Инструментальная панель для пакетных действий -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="d-flex align-items-center gap-3">
            {% if is_paginated %}
                <span class="text-muted">
                    Показано {{ page_obj.start_index }}–{{ page_obj.end_index }} из {{ page_obj.paginator.count }}
                </span>
            {% else %}
                <span class="text-muted">Всего: {{ items|length }}</span>
            {% endif %}
            
            <!-- Dropdown для выбора всех отфильтрованных -->
            <div class="btn-group" id="select-all-dropdown-group" style="display: none;">
                <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" 
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-check2-square"></i> Выбрать
                </button>
                <ul class="dropdown-menu">
                    <li>
                        <a class="dropdown-item" href="#" onclick="document.getElementById('select-all-checkbox').click(); return false;">
                            <i class="bi bi-check2"></i> Все на странице
                        </a>
                    </li>
                    {% if is_paginated %}
                    <li>
                        <a class="dropdown-item" href="#" onclick="window.BatchSelection.selectAllFiltered(); return false;">
                            <i class="bi bi-check2-all"></i> Все отфильтрованные ({{ page_obj.paginator.count }})
                        </a>
                    </li>
                    {% endif %}
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <a class="dropdown-item" href="#" onclick="window.BatchSelection.clearSelection(); return false;">
                            <i class="bi bi-x-square"></i> Снять выбор
                        </a>
                    </li>
                </ul>
            </div>
        </div>
        <div class="btn-group">
            <button type="button" class="btn btn-outline-secondary" id="batch-actions-btn" disabled>
                <i class="bi bi-gear-fill"></i> Действия над выбранными (<span id="selection-count">0</span>)
            </button>
            <button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" 
                    id="batch-actions-dropdown" data-bs-toggle="dropdown" aria-expanded="false" disabled>
                <span class="visually-hidden">Открыть меню</span>
            </button>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="batch-actions-dropdown">
                <li>
                    <a class="dropdown-item" href="#" id="bulk-category-action">
                        <i class="bi bi-bookmark-fill"></i> Изменить категории
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item" href="#" id="bulk-recommerce-sync">
                        <i class="bi bi-arrow-repeat"></i> Синхронизация с Recommerce
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-striped table-hover align-middle">
            <thead class="table-dark">
                <tr>
                    <th style="width: 50px;">
                        <input type="checkbox" id="select-all-checkbox" class="form-check-input" 
                               title="Выбрать все на странице">
                    </th>
                    <th style="width: 80px;">Фото</th>
                    <th>Название</th>
                    <th style="width: 120px;">Артикул</th>
                    <th style="width: 80px;">Тип</th>
                    <th>Категория</th>
                    <th style="width: 150px;">Теги</th>
                    <th style="width: 130px;">Цена</th>
                    <th style="width: 120px;">Остаток</th>
                    <th style="width: 100px;">Статус</th>
                    <th style="width: 150px;">Действия</th>
                </tr>
            </thead>
            <tbody>
                {% for item in items %}
                <tr>
                    <td>
                        <input type="checkbox" name="selected_items" 
                               value="{{ item.item_type }}:{{ item.pk }}" 
                               class="form-check-input item-checkbox"
                               data-item-type="{{ item.item_type }}"
                               data-item-id="{{ item.pk }}"
                               data-item-name="{{ item.name }}">
                    </td>
                    <td>
                        {% if item.photos.all %}
                            {% with photo=item.photos.first %}
                                <img src="{{ photo.get_thumbnail_url }}" alt="{{ item.name }}" 
                                     class="img-thumbnail rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            {% endwith %}
                        {% else %}
                            <span class="text-muted small">Нет фото</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <a href="{% url 'products:product-detail' item.pk %}">{{ item.name }}</a>
                        {% else %}
                            <a href="{% url 'products:productkit-detail' item.pk %}">{{ item.name }}</a>
                        {% endif %}
                        <div class="mt-1">
                            {% if item.is_new %}<span class="badge bg-warning text-dark" title="Новинка"><i class="bi bi-stars"></i></span>{% endif %}
                            {% if item.is_popular %}<span class="badge bg-danger" title="Популярный"><i class="bi bi-fire"></i></span>{% endif %}
                            {% if item.is_special %}<span class="badge bg-success" title="Спецпредложение"><i class="bi bi-percent"></i></span>{% endif %}
                        </div>
                    </td>
                    <td><code class="small">{{ item.sku }}</code></td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <span class="badge bg-success" title="Товар"><i class="bi bi-box"></i></span>
                        {% else %}
                            <span class="badge bg-info" title="Комплект"><i class="bi bi-box-seam"></i></span>
                        {% endif %}
                    </td>
                    <td>
                        {% for category in item.categories.all %}
                            <span class="badge bg-secondary">{{ category.name }}</span>
                        {% empty %}
                            <span class="text-muted">-</span>
                        {% endfor %}
                    </td>
                    <td title="{% if item.tags.all|length %}{% for t in item.tags.all %}{{ t.name }}{% if not forloop.last %}, {% endif %}{% endfor %}{% else %}-{% endif %}">
                        {% for tag in item.tags.all|slice:":2" %}
                            <span class="badge bg-primary">{{ tag.name }}</span>
                        {% empty %}
                            <span class="text-muted">-</span>
                        {% endfor %}
                        {% with total=item.tags.all|length %}
                            {% if total > 2 %}
                                <span class="text-muted">…</span>
                            {% endif %}
                        {% endwith %}
                    </td>
                    <td>
                        {% if item.sale_price %}
                            <div class="text-decoration-line-through text-muted small">{{ item.price|floatformat:2 }} руб.</div>
                            <strong class="text-danger">{{ item.sale_price|floatformat:2 }} руб.</strong>
                        {% else %}
                            <strong>{{ item.price|floatformat:2 }} руб.</strong>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <strong class="{% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">{{ item.total_free|floatformat:-2 }}</strong>{% if item.total_reserved > 0 %}<small class="text-muted"> / {{ item.total_available|floatformat:-2 }}</small>
                                <small class="text-warning d-block">{{ item.total_reserved|floatformat:-2 }} в резерве</small>
                            {% endif %}
                        {% elif item.item_type == 'kit' %}
                            <strong class="{% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">{{ item.total_free|floatformat:0 }}</strong> <small class="text-muted">компл.</small>
                        {% else %}
                            <span class="text-muted">-</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.status == 'active' %}
                            <span class="badge bg-success">Активный</span>
                        {% elif item.status == 'archived' %}
                            <span class="badge bg-warning text-dark">Архивный</span>
                        {% elif item.status == 'discontinued' %}
                            <span class="badge bg-danger">Снят</span>
                        {% else %}
                            <span class="badge bg-secondary">{{ item.get_status_display }}</span>
                        {% endif %}
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            {% if item.item_type == 'product' %}
                                <a href="{% url 'products:product-detail' item.pk %}" 
                                   class="btn btn-outline-info" title="Просмотр">
                                    <i class="bi bi-eye"></i>
                                </a>
                                {% if perms.products.change_product %}
                                <a href="{% url 'products:product-update' item.pk %}" 
                                   class="btn btn-outline-primary" title="Изменить">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                {% endif %}
                                {% if perms.products.delete_product %}
                                <a href="{% url 'products:product-delete' item.pk %}" 
                                   class="btn btn-outline-danger" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </a>
                                {% endif %}
                            {% else %}
                                <a href="{% url 'products:productkit-detail' item.pk %}" 
                                   class="btn btn-outline-info" title="Просмотр">
                                    <i class="bi bi-eye"></i>
                                </a>
                                {% if perms.products.change_productkit %}
                                <a href="{% url 'products:productkit-update' item.pk %}" 
                                   class="btn btn-outline-primary" title="Изменить">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                {% endif %}
                                {% if perms.products.delete_productkit %}
                                <a href="{% url 'products:productkit-delete' item.pk %}" 
                                   class="btn btn-outline-danger" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </a>
                                {% endif %}
                            {% endif %}
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    {% if is_paginated %}
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page=1{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Первая
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Предыдущая
                    </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 }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Следующая
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Последняя
                    </a>
                </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
    {% else %}
    <div class="alert alert-info">
        <h4><i class="bi bi-info-circle"></i> Товары не найдены</h4>
        <p>В данный момент нет товаров или комплектов, соответствующих выбранным фильтрам.</p>
        <div class="mt-3">
            {% if perms.products.add_product %}
            <a href="{% url 'products:product-create' %}" class="btn btn-primary me-2">
                <i class="bi bi-plus-circle"></i> Создать товар
            </a>
            {% endif %}
            {% if perms.products.add_productkit %}
            <a href="{% url 'products:productkit-create' %}" class="btn btn-outline-primary">
                <i class="bi bi-plus-circle"></i> Создать комплект
            </a>
            {% endif %}
        </div>
    </div>
    {% endif %}
</div>

{% include "products/includes/recommerce_sync_modal.html" %}

<!-- Модальное окно для массового изменения категорий -->
<div class="modal fade" id="bulkCategoryModal" tabindex="-1" aria-labelledby="bulkCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkCategoryModalLabel">
                    <i class="bi bi-bookmark-fill"></i> Изменить категории для выбранных товаров
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <!-- Информация о выбранных товарах -->
                <div class="alert alert-info mb-3">
                    <i class="bi bi-info-circle"></i> <strong>Выбрано:</strong> <span id="selectedItemsCount">0</span> товаров
                    <span id="selectedItemsBreakdown" class="ms-2 text-muted"></span>
                </div>

                <!-- Режим изменения категорий -->
                <div class="mb-4">
                    <label class="form-label fw-bold">Что сделать с категориями выбранных товаров?</label>

                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeAdd" value="add" checked>
                        <label class="form-check-label" for="bulkCategoryModeAdd">
                            Добавить выбранные категории к существующим
                        </label>
                    </div>

                    <div class="form-check mt-2">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeReplace" value="replace">
                        <label class="form-check-label" for="bulkCategoryModeReplace">
                            Заменить существующие категории выбранными
                        </label>
                    </div>

                    <div class="form-check mt-2">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeClear" value="clear">
                        <label class="form-check-label text-danger" for="bulkCategoryModeClear">
                            <strong>Удалить все категории</strong>
                        </label>
                    </div>

                    <div id="bulkCategoryModeHint" class="form-text text-muted mt-2">
                        Добавленные категории будут присоединены к уже существующим.
                    </div>
                </div>

                <!-- Выбор категорий -->
                <div class="mb-3" id="bulkCategoryListSection">
                    <label class="form-label fw-bold">Выберите категории:</label>
                    
                    <!-- Поиск по категориям -->
                    <input type="text" class="form-control mb-2" id="categorySearchInput" 
                           placeholder="Поиск категорий...">
                    
                    <!-- Список категорий -->
                    <div id="categoryListContainer" style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 0.25rem; padding: 0.5rem;">
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Загрузка...</span>
                            </div>
                            <div class="mt-2 text-muted">Загрузка категорий...</div>
                        </div>
                    </div>
                </div>

                <!-- Сообщения об ошибках -->
                <div id="bulkCategoryError" class="alert alert-danger d-none" role="alert"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle"></i> Отмена
                </button>
                <button type="button" class="btn btn-primary" id="applyBulkCategoriesBtn" disabled>
                    <i class="bi bi-check2-circle"></i> Применить
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{% load static %}
<script src="{% static 'products/js/batch-selection.js' %}?v=1.2"></script>
<script src="{% static 'products/js/bulk-category-modal.js' %}?v=1.6"></script>
<script src="{% static 'products/js/recommerce-sync.js' %}?v=1.1"></script>
{% endblock %}
