{% extends 'base.html' %}

{% block title %}{% if object %}Редактировать атрибут{% else %}Создать атрибут{% endif %}{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0">
                <div class="card-body p-4">
                    <h5 class="text-center mb-4">
                        <i class="bi bi-sliders{% if not object %}-fill{% endif %} text-primary"></i>
                        {% if object %}Редактировать атрибут{% else %}Новый атрибут{% endif %}
                    </h5>

                    <form method="post">
                        {% csrf_token %}

                        <!-- Основные поля атрибута -->
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <label class="form-label">Название <span class="text-danger">*</span></label>
                                {{ form.name }}
                                {% if form.name.errors %}
                                <small class="text-danger">{{ form.name.errors.0 }}</small>
                                {% endif %}
                            </div>
                            <div class="col-md-4">
                                <label class="form-label"><i class="bi bi-arrows-vertical"></i> Позиция</label>
                                {{ form.position }}
                                <small class="text-muted">Порядок сортировки</small>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Slug (URL)</label>
                            {{ form.slug }}
                            <small class="text-muted">{{ form.slug.help_text }}</small>
                            {% if form.slug.errors %}
                            <small class="text-danger d-block">{{ form.slug.errors.0 }}</small>
                            {% endif %}
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Описание</label>
                            {{ form.description }}
                        </div>

                        <!-- Значения атрибута (inline formset) -->
                        <hr>
                        <h6 class="mb-3">
                            <i class="bi bi-list-ul"></i> Значения атрибута
                        </h6>

                        {{ value_formset.management_form }}

                        <!-- Заголовки столбцов -->
                        <div class="row align-items-center g-2 mb-2 small text-muted fw-medium">
                            <div class="col">Значение</div>
                            <div class="col-auto" style="width: 120px;">Slug</div>
                            <div class="col-auto" style="width: 80px;" title="Порядок сортировки"><i class="bi bi-arrows-vertical"></i> Поз.</div>
                            <div class="col-auto" style="width: 40px;"></div>
                        </div>

                        <div id="value-formset">
                            {% for value_form in value_formset %}
                            <div class="value-row mb-2 {% if value_form.instance.pk %}{% else %}empty-form{% endif %}">
                                <div class="row align-items-center g-2">
                                    <div class="col">
                                        {{ value_form.value }}
                                        {% if value_form.value.errors %}
                                        <small class="text-danger">{{ value_form.value.errors.0 }}</small>
                                        {% endif %}
                                    </div>
                                    <div class="col-auto" style="width: 120px;">
                                        {{ value_form.slug }}
                                    </div>
                                    <div class="col-auto" style="width: 80px;">
                                        {{ value_form.position }}
                                    </div>
                                    <div class="col-auto">
                                        {% if value_form.instance.pk %}
                                        <div class="form-check">
                                            {{ value_form.DELETE }}
                                            <label class="form-check-label text-danger small" for="{{ value_form.DELETE.id_for_label }}">
                                                <i class="bi bi-trash"></i>
                                            </label>
                                        </div>
                                        {% else %}
                                        <button type="button" class="btn btn-outline-danger btn-sm remove-value-row">
                                            <i class="bi bi-x"></i>
                                        </button>
                                        {% endif %}
                                    </div>
                                    {{ value_form.id }}
                                </div>
                            </div>
                            {% endfor %}
                        </div>

                        <button type="button" id="add-value-btn" class="btn btn-outline-secondary btn-sm mt-2">
                            <i class="bi bi-plus"></i> Добавить значение
                        </button>

                        <hr class="my-4">

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-check2"></i>
                                {% if object %}Сохранить{% else %}Создать{% endif %}
                            </button>
                            <a href="{% url 'products:attribute-list' %}" class="btn btn-light btn-sm">Отмена</a>
                        </div>
                    </form>

                    {% if object %}
                    <hr class="my-3">
                    <small class="text-muted d-block text-center">
                        <i class="bi bi-clock-history"></i> Обновлено: {{ object.updated_at|date:"d.m.Y H:i" }}
                    </small>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const formset = document.getElementById('value-formset');
    const addBtn = document.getElementById('add-value-btn');
    const totalForms = document.querySelector('[name="values-TOTAL_FORMS"]');

    // Шаблон для новой строки
    function createValueRow(index) {
        const row = document.createElement('div');
        row.className = 'value-row mb-2';
        row.innerHTML = `
            <div class="row align-items-center g-2">
                <div class="col">
                    <input type="text" name="values-${index}-value" class="form-control form-control-sm" placeholder="Например: 50">
                </div>
                <div class="col-auto" style="width: 120px;">
                    <input type="text" name="values-${index}-slug" class="form-control form-control-sm" placeholder="Авто">
                </div>
                <div class="col-auto" style="width: 80px;">
                    <input type="number" name="values-${index}-position" value="0" class="form-control form-control-sm" style="width: 70px;">
                </div>
                <div class="col-auto">
                    <button type="button" class="btn btn-outline-danger btn-sm remove-value-row">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
                <input type="hidden" name="values-${index}-id" value="">
            </div>
        `;
        return row;
    }

    // Добавление новой строки
    addBtn.addEventListener('click', function() {
        const currentTotal = parseInt(totalForms.value);
        const newRow = createValueRow(currentTotal);
        formset.appendChild(newRow);
        totalForms.value = currentTotal + 1;

        // Фокус на новое поле
        newRow.querySelector('input[type="text"]').focus();
    });

    // Удаление строки (делегирование событий)
    formset.addEventListener('click', function(e) {
        if (e.target.closest('.remove-value-row')) {
            const row = e.target.closest('.value-row');
            row.remove();
        }
    });
});
</script>
{% endblock %}
