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

{% block title %}Menü Düzenle: {{ menu.name }}{% endblock %}
{% block page_title %}Menü Düzenle: {{ menu.name }}{% endblock %}

{% block body %}
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {# Left column - Menu details & items (8/12) #}
        <div class="lg:col-span-8 space-y-6">
            {# Menu Details Form #}
            <form method="post" action="{{ path('admin_menu_edit', {id: menu.id}) }}">
                <input type="hidden" name="_token" value="{{ csrf_token('menu_form') }}">
                <div class="card">
                    <div class="card-header flex items-center justify-between">
                        <h3 class="card-title">Menü Bilgileri</h3>
                    </div>
                    <div class="card-body space-y-4">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="name" class="form-label">Menü Adı <span class="text-red-500">*</span></label>
                                <input type="text" id="name" name="name" required
                                       value="{{ menu.name }}"
                                       class="form-input w-full">
                            </div>
                            <div>
                                <label for="slug" class="form-label">Slug</label>
                                <input type="text" id="slug" name="slug"
                                       value="{{ menu.slug }}"
                                       class="form-input w-full">
                            </div>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="location" class="form-label">Konum</label>
                                <select id="location" name="location" class="form-input w-full">
                                    <option value="header" {{ menu.location == 'header' ? 'selected' : '' }}>Header</option>
                                    <option value="footer" {{ menu.location == 'footer' ? 'selected' : '' }}>Footer</option>
                                    <option value="sidebar" {{ menu.location == 'sidebar' ? 'selected' : '' }}>Sidebar</option>
                                    <option value="mobile" {{ menu.location == 'mobile' ? 'selected' : '' }}>Mobil</option>
                                </select>
                            </div>
                            <div class="flex items-end">
                                <label class="flex items-center gap-3 cursor-pointer pb-2">
                                    <input type="checkbox" name="is_active" value="1"
                                           {{ menu.isActive ? 'checked' : '' }}
                                           class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                                    <span class="form-label mb-0">Aktif</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="card-body border-t border-gray-200 pt-4">
                        <button type="submit" class="btn-primary">
                            <i class="fas fa-save mr-2"></i> Menüyü Güncelle
                        </button>
                    </div>
                </div>
            </form>

            {# Menu Items List #}
            <div class="card">
                <div class="card-header flex items-center justify-between">
                    <h3 class="card-title">Menü Öğeleri</h3>
                    <span class="text-sm text-gray-500">{{ items|length }} öğe</span>
                </div>
                <div class="card-body p-0">
                    {% if items|length > 0 %}
                        <div id="menu-items-list" data-menu-id="{{ menu.id }}" data-reorder-url="{{ path('admin_menu_items_reorder', {menuId: menu.id}) }}">
                            {% for item in items %}
                                {# Top-level item #}
                                <div class="menu-item-row border-b border-gray-100 last:border-b-0"
                                     data-item-id="{{ item.id }}" data-parent-id="">
                                    <div class="flex items-center gap-3 px-4 py-3 hover:bg-gray-50 group">
                                        <div class="cursor-grab text-gray-400 hover:text-gray-600 drag-handle">
                                            <i class="fas fa-grip-vertical"></i>
                                        </div>
                                        {% if item.icon %}
                                            <i class="{{ item.icon }} text-gray-500"></i>
                                        {% endif %}
                                        <div class="flex-1 min-w-0">
                                            <span class="font-medium text-gray-900">{{ item.title }}</span>
                                            {% if item.url %}
                                                <span class="text-xs text-gray-400 ml-2 truncate">{{ item.url }}</span>
                                            {% endif %}
                                        </div>
                                        <span class="inline-flex items-center rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">
                                            {{ item.type }}
                                        </span>
                                        {% if item.target == '_blank' %}
                                            <i class="fas fa-external-link-alt text-xs text-gray-400" title="Yeni sekmede aç"></i>
                                        {% endif %}
                                        {% if not item.isActive %}
                                            <span class="badge-gray">Pasif</span>
                                        {% endif %}
                                        <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <form method="post" action="{{ path('admin_menu_item_delete', {id: item.id}) }}"
                                                  onsubmit="return confirm('Bu menü öğesini silmek istediğinize emin misiniz?')">
                                                <input type="hidden" name="_token" value="{{ csrf_token('delete_menu_item_' ~ item.id) }}">
                                                <button type="submit" class="text-red-500 hover:text-red-700 p-1" title="Sil">
                                                    <i class="fas fa-trash-alt text-sm"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </div>

                                    {# Children (nested items) #}
                                    {% if item.children|length > 0 %}
                                        <div class="children-list">
                                            {% for child in item.children %}
                                                <div class="menu-item-row" data-item-id="{{ child.id }}" data-parent-id="{{ item.id }}">
                                                    <div class="flex items-center gap-3 px-4 py-2.5 pl-12 hover:bg-gray-50 group bg-gray-50/50 border-t border-gray-100">
                                                        <div class="cursor-grab text-gray-400 hover:text-gray-600 drag-handle">
                                                            <i class="fas fa-grip-vertical text-sm"></i>
                                                        </div>
                                                        <i class="fas fa-level-up-alt fa-rotate-90 text-xs text-gray-300"></i>
                                                        {% if child.icon %}
                                                            <i class="{{ child.icon }} text-gray-500 text-sm"></i>
                                                        {% endif %}
                                                        <div class="flex-1 min-w-0">
                                                            <span class="text-sm text-gray-700">{{ child.title }}</span>
                                                            {% if child.url %}
                                                                <span class="text-xs text-gray-400 ml-2 truncate">{{ child.url }}</span>
                                                            {% endif %}
                                                        </div>
                                                        <span class="inline-flex items-center rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-500">
                                                            {{ child.type }}
                                                        </span>
                                                        {% if not child.isActive %}
                                                            <span class="badge-gray text-xs">Pasif</span>
                                                        {% endif %}
                                                        <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                            <form method="post" action="{{ path('admin_menu_item_delete', {id: child.id}) }}"
                                                                  onsubmit="return confirm('Bu menü öğesini silmek istediğinize emin misiniz?')">
                                                                <input type="hidden" name="_token" value="{{ csrf_token('delete_menu_item_' ~ child.id) }}">
                                                                <button type="submit" class="text-red-500 hover:text-red-700 p-1" title="Sil">
                                                                    <i class="fas fa-trash-alt text-xs"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            {% endfor %}
                                        </div>
                                    {% endif %}
                                </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center text-gray-500 py-12">
                            <i class="fas fa-list text-4xl text-gray-300 mb-3 block"></i>
                            Henüz menü öğesi eklenmemiş.
                            <br>
                            <span class="text-sm text-gray-400 mt-1 inline-block">Sağ taraftaki formu kullanarak öğe ekleyin.</span>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        {# Right column - Add item form (4/12) #}
        <div class="lg:col-span-4 space-y-6">
            {# Add Item Form #}
            <form method="post" action="{{ path('admin_menu_item_add', {menuId: menu.id}) }}">
                <input type="hidden" name="_token" value="{{ csrf_token('menu_item_form') }}">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Yeni Öğe Ekle</h3>
                    </div>
                    <div class="card-body space-y-4">
                        {# Title #}
                        <div>
                            <label for="item_title" class="form-label">Başlık <span class="text-red-500">*</span></label>
                            <input type="text" id="item_title" name="title" required
                                   class="form-input w-full"
                                   placeholder="Menü öğesi başlığı">
                        </div>

                        {# URL #}
                        <div>
                            <label for="item_url" class="form-label">URL</label>
                            <input type="text" id="item_url" name="url"
                                   class="form-input w-full"
                                   placeholder="https://ornek.com veya /sayfa">
                        </div>

                        {# Type #}
                        <div>
                            <label for="item_type" class="form-label">Tür</label>
                            <select id="item_type" name="type" class="form-input w-full">
                                <option value="custom">Özel Link</option>
                                <option value="category">Kategori</option>
                                <option value="page">Sayfa</option>
                                <option value="tag">Etiket</option>
                            </select>
                        </div>

                        {# Reference ID #}
                        <div>
                            <label for="item_reference_id" class="form-label">Referans ID</label>
                            <input type="number" id="item_reference_id" name="reference_id"
                                   class="form-input w-full"
                                   placeholder="Kategori, sayfa veya etiket ID">
                            <p class="text-xs text-gray-500 mt-1">Tür olarak kategori, sayfa veya etiket seçildiğinde ilgili öğenin ID'si.</p>
                        </div>

                        {# Parent #}
                        <div>
                            <label for="item_parent_id" class="form-label">Üst Öğe</label>
                            <select id="item_parent_id" name="parent_id" class="form-input w-full">
                                <option value="">-- Üst öğe yok (Ana seviye) --</option>
                                {% for item in items %}
                                    <option value="{{ item.id }}">{{ item.title }}</option>
                                {% endfor %}
                            </select>
                        </div>

                        {# Icon #}
                        <div>
                            <label for="item_icon" class="form-label">İkon</label>
                            <input type="text" id="item_icon" name="icon"
                                   class="form-input w-full"
                                   placeholder="fas fa-home">
                            <p class="text-xs text-gray-500 mt-1">FontAwesome ikon sınıfı.</p>
                        </div>

                        {# CSS Class #}
                        <div>
                            <label for="item_css_class" class="form-label">CSS Sınıfı</label>
                            <input type="text" id="item_css_class" name="css_class"
                                   class="form-input w-full"
                                   placeholder="Opsiyonel CSS sınıfı">
                        </div>

                        {# Target #}
                        <div>
                            <label for="item_target" class="form-label">Açılış Hedefi</label>
                            <select id="item_target" name="target" class="form-input w-full">
                                <option value="_self">Aynı Sekmede (_self)</option>
                                <option value="_blank">Yeni Sekmede (_blank)</option>
                            </select>
                        </div>

                        {# Is Active #}
                        <div>
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" name="is_active" value="1" checked
                                       class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                                <span class="form-label mb-0">Aktif</span>
                            </label>
                        </div>
                    </div>
                    <div class="card-body border-t border-gray-200 pt-4">
                        <button type="submit" class="btn-primary w-full justify-center">
                            <i class="fas fa-plus mr-2"></i> Öğe Ekle
                        </button>
                    </div>
                </div>
            </form>

            {# Back button #}
            <a href="{{ path('admin_menus') }}" class="btn-outline w-full justify-center">
                <i class="fas fa-arrow-left mr-2"></i> Menü Listesine Dön
            </a>
        </div>
    </div>

    {% block javascripts %}
        {{ parent() }}
        <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const listEl = document.getElementById('menu-items-list');
                if (!listEl) return;

                const reorderUrl = listEl.dataset.reorderUrl;

                // Initialize SortableJS on the main list
                new Sortable(listEl, {
                    handle: '.drag-handle',
                    animation: 150,
                    ghostClass: 'bg-blue-50',
                    dragClass: 'shadow-lg',
                    onEnd: function () {
                        saveOrder();
                    }
                });

                // Also initialize on children lists
                document.querySelectorAll('.children-list').forEach(function (childList) {
                    new Sortable(childList, {
                        handle: '.drag-handle',
                        animation: 150,
                        ghostClass: 'bg-blue-50',
                        onEnd: function () {
                            saveOrder();
                        }
                    });
                });

                function saveOrder() {
                    const items = [];
                    let position = 0;

                    listEl.querySelectorAll('.menu-item-row').forEach(function (row) {
                        items.push({
                            id: parseInt(row.dataset.itemId),
                            parent_id: row.dataset.parentId ? parseInt(row.dataset.parentId) : null,
                            position: position++
                        });
                    });

                    fetch(reorderUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: JSON.stringify({ items: items })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            console.error('Sıralama kaydedilemedi:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Sıralama hatası:', error);
                    });
                }
            });
        </script>
    {% endblock %}
{% endblock %}
