{% extends 'base.html' %}

{% block title %}Атрибут: {{ attribute.name }}{% 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 justify-content-between mb-4">
                <div>
                    <a href="{% url 'products:attribute-list' %}" class="text-decoration-none text-muted small">
                        <i class="bi bi-arrow-left"></i> Все атрибуты
                    </a>
                    <h4 class="mb-0 mt-1">
                        <i class="bi bi-sliders text-primary"></i> {{ attribute.name }}
                    </h4>
                    <small class="text-muted">{{ attribute.slug }}</small>
                </div>
                <div class="btn-group">
                    <a href="{% url 'products:attribute-update' attribute.pk %}" class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-pencil"></i> Изменить
                    </a>
                    <a href="{% url 'products:attribute-delete' attribute.pk %}" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-trash"></i>
                    </a>
                </div>
            </div>

            {% if attribute.description %}
            <p class="text-muted mb-4">{{ attribute.description }}</p>
            {% endif %}

            <!-- Значения атрибута -->
            <div class="card shadow-sm border-0">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-list-ul"></i> Значения ({{ values|length }})</span>
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addValueModal">
                        <i class="bi bi-plus"></i> Добавить
                    </button>
                </div>
                <div class="card-body p-0">
                    {% if values %}
                    <ul class="list-group list-group-flush">
                        {% for value in values %}
                        <li class="list-group-item d-flex justify-content-between align-items-center py-2">
                            <div>
                                <span class="fw-medium">{{ value.value }}</span>
                                <small class="text-muted ms-2">{{ value.slug }}</small>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-light text-dark" title="Порядок сортировки"><i class="bi bi-arrows-vertical"></i> {{ value.position }}</span>
                                <button type="button" class="btn btn-outline-danger btn-sm py-0 px-1 delete-value-btn"
                                        data-value-id="{{ value.pk }}" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </li>
                        {% endfor %}
                    </ul>
                    {% else %}
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-list-ul fs-2 opacity-25"></i>
                        <p class="mb-0 mt-2">Значений пока нет</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Метаданные -->
            <div class="text-muted small mt-3 text-center">
                <i class="bi bi-clock-history"></i>
                Создан: {{ attribute.created_at|date:"d.m.Y H:i" }} |
                Обновлен: {{ attribute.updated_at|date:"d.m.Y H:i" }}
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно добавления значения -->
<div class="modal fade" id="addValueModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Добавить значение</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Значение</label>
                    <input type="text" id="new-value-input" class="form-control" placeholder="Например: 50">
                </div>
                <div id="add-value-message"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Отмена</button>
                <button type="button" class="btn btn-primary btn-sm" id="add-value-btn">
                    <i class="bi bi-plus"></i> Добавить
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const addBtn = document.getElementById('add-value-btn');
    const valueInput = document.getElementById('new-value-input');
    const messageDiv = document.getElementById('add-value-message');

    // Добавление значения
    addBtn.addEventListener('click', async function() {
        const value = valueInput.value.trim();
        if (!value) {
            showMessage('Введите значение', 'danger');
            return;
        }

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

        try {
            const response = await fetch('{% url "products:attribute-add-value" attribute.pk %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({value: value})
            });
            const data = await response.json();

            if (data.success) {
                showMessage('Значение добавлено', 'success');
                setTimeout(() => window.location.reload(), 500);
            } else {
                showMessage(data.error, 'danger');
                resetBtn();
            }
        } catch (error) {
            showMessage('Ошибка сети', 'danger');
            resetBtn();
        }
    });

    // Удаление значения
    document.querySelectorAll('.delete-value-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            if (!confirm('Удалить это значение?')) return;

            const valueId = this.dataset.valueId;
            this.disabled = true;

            try {
                const response = await fetch(`{% url "products:attribute-delete-value" attribute.pk 0 %}`.replace('/0/', `/${valueId}/`), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                });
                const data = await response.json();

                if (data.success) {
                    this.closest('li').remove();
                } else {
                    alert(data.error);
                    this.disabled = false;
                }
            } catch (error) {
                alert('Ошибка сети');
                this.disabled = false;
            }
        });
    });

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

    function resetBtn() {
        addBtn.disabled = false;
        addBtn.innerHTML = '<i class="bi bi-plus"></i> Добавить';
        valueInput.focus();
    }

    // Enter для добавления
    valueInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            addBtn.click();
        }
    });
});
</script>
{% endblock %}
