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

{% block title %}{{ menu ? 'Menu Duzenle: ' ~ menu.name : 'Yeni Menu' }}{% endblock %}
{% block page_title %}{{ menu ? 'Menu Duzenle: ' ~ menu.name : 'Yeni Menu Olustur' }}{% 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="{{ menu ? path('admin_menu_edit', {id: menu.id}) : path('admin_menu_create') }}">
                <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">Menu 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">Menu Adi <span class="text-red-500">*</span></label>
                                <input type="text" id="name" name="name" required
                                       value="{{ menu ? menu.name : '' }}"
                                       class="form-input w-full"
                                       placeholder="Menu adi">
                            </div>
                            <div>
                                <label for="location" class="form-label">Konum <span class="text-red-500">*</span></label>
                                <select id="location" name="location" class="form-input w-full">
                                    <option value="header" {{ menu and menu.location == 'header' ? 'selected' : (not menu ? 'selected' : '') }}>Header</option>
                                    <option value="footer" {{ menu and menu.location == 'footer' ? 'selected' : '' }}>Footer</option>
                                    <option value="sidebar" {{ menu and menu.location == 'sidebar' ? 'selected' : '' }}>Sidebar</option>
                                    <option value="mobile" {{ menu and menu.location == 'mobile' ? 'selected' : '' }}>Mobil</option>
                                </select>
                            </div>
                        </div>
                        <div class="flex items-center gap-4">
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" name="is_active" value="1"
                                       {{ (menu and menu.isActive) or not menu ? '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">
                            <i class="fas fa-save mr-2"></i> {{ menu ? 'Menuyu Guncelle' : 'Menu Olustur' }}
                        </button>
                    </div>
                </div>
            </form>

            {# Menu Items List (only shown when editing) #}
            {% if menu is not null %}
                <div class="card">
                    <div class="card-header flex items-center justify-between">
                        <h3 class="card-title">Menu Ogeleri</h3>
                        <span class="text-sm text-gray-500">{{ items|default([])|length }} oge</span>
                    </div>
                    <div class="card-body p-0">
                        {% if items|default([])|length > 0 %}
                            <div id="menu-items-list" data-menu-id="{{ menu.id }}" data-save-url="{{ path('admin_menu_items', {id: menu.id}) }}">
                                {% for item in items %}
                                    <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>
                                            {% if item.target == '_blank' %}
                                                <i class="fas fa-external-link-alt text-xs text-gray-400" title="Yeni sekmede ac"></i>
                                            {% endif %}
                                            {% if not item.isActive %}
                                                <span class="badge-gray">Pasif</span>
                                            {% endif %}
                                        </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>
                                                            {% if not child.isActive %}
                                                                <span class="badge-gray text-xs">Pasif</span>
                                                            {% endif %}
                                                        </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>
                                Henuz menu ogesi eklenmemis.
                                <br>
                                <span class="text-sm text-gray-400 mt-1 inline-block">Sag taraftaki formu kullanarak oge ekleyin.</span>
                            </div>
                        {% endif %}
                    </div>
                </div>
            {% endif %}
        </div>

        {# Right column (4/12) #}
        <div class="lg:col-span-4 space-y-6">
            {# Add Item Form (only shown when editing) #}
            {% if menu is not null %}
                <div class="card" x-data="{ showForm: true }">
                    <div class="card-header cursor-pointer" @click="showForm = !showForm">
                        <h3 class="card-title"><i class="fas fa-plus-circle mr-2"></i> Yeni Oge Ekle</h3>
                    </div>
                    <div class="card-body space-y-4" x-show="showForm">
                        <div>
                            <label for="item_title" class="form-label">Baslik <span class="text-red-500">*</span></label>
                            <input type="text" id="item_title" class="form-input w-full" placeholder="Menu ogesi basligi">
                        </div>
                        <div>
                            <label for="item_url" class="form-label">URL</label>
                            <input type="text" id="item_url" class="form-input w-full" placeholder="https://ornek.com veya /sayfa">
                        </div>
                        <div>
                            <label for="item_target" class="form-label">Acilis Hedefi</label>
                            <select id="item_target" class="form-input w-full">
                                <option value="_self">Ayni Sekmede (_self)</option>
                                <option value="_blank">Yeni Sekmede (_blank)</option>
                            </select>
                        </div>
                        <div>
                            <label for="item_icon" class="form-label">Ikon</label>
                            <input type="text" id="item_icon" class="form-input w-full" placeholder="fas fa-home">
                            <p class="text-xs text-gray-500 mt-1">FontAwesome ikon sinifi.</p>
                        </div>
                        <div>
                            <label for="item_css_class" class="form-label">CSS Sinifi</label>
                            <input type="text" id="item_css_class" class="form-input w-full" placeholder="Opsiyonel CSS sinifi">
                        </div>
                        <button type="button" id="btn-add-item" class="btn-primary w-full justify-center">
                            <i class="fas fa-plus mr-2"></i> Oge Ekle
                        </button>
                    </div>
                </div>
            {% endif %}

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

    {% if menu is not null %}
    {% 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 saveUrl = listEl.dataset.saveUrl;

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

                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(saveUrl, {
                        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('Siralama kaydedilemedi:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Siralama hatasi:', error);
                    });
                }

                // Add item button
                const btnAdd = document.getElementById('btn-add-item');
                if (btnAdd) {
                    btnAdd.addEventListener('click', function () {
                        const title = document.getElementById('item_title').value.trim();
                        if (!title) {
                            alert('Baslik alani zorunludur.');
                            return;
                        }

                        const newItem = {
                            title: title,
                            url: document.getElementById('item_url').value.trim(),
                            target: document.getElementById('item_target').value,
                            icon: document.getElementById('item_icon').value.trim(),
                            css_class: document.getElementById('item_css_class').value.trim(),
                            is_active: true,
                            parent_id: null
                        };

                        // Get all current items + new one
                        const items = [];
                        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
                            });
                        });
                        items.push(newItem);

                        fetch(saveUrl, {
                            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) {
                                location.reload();
                            } else {
                                alert('Hata: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Oge ekleme hatasi:', error);
                        });
                    });
                }
            });
        </script>
    {% endblock %}
    {% endif %}
{% endblock %}
