import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";

class WordpressView extends BaseView {
    static title = "مدیریت منوها";

    constructor(props = {}) {
        super(props);
        this.api = props.api;
    }

    async render(container) {
        await super.render(container);
        const body = this.ref("body");

        try {
            const response = await this.api.get("/wordpress/wp-menus");
            const menus = response.items || [];

            body.innerHTML = `
                <div class="wp-menus-wrapper" style="padding: 15px;">
                    ${menus.map(menu => `
                        <div class="menu-container" style="margin-bottom: 10px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;">
                            <div class="menu-header" style="background: #f0f0f0; padding: 12px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd;" 
                                 onclick="this.nextElementSibling.style.display = (this.nextElementSibling.style.display === 'none' ? 'block' : 'none')">
                                <h3 style="margin: 0; font-size: 16px;">منو: ${menu.name} <small style="color: #666;">(ID: ${menu.id})</small></h3>
                                <span>▼</span>
                            </div>
                            <ul class="menu-items-list" style="list-style: none; padding: 0; margin: 0; display: none; background: #fff;">
                                ${menu.items.map(item => `
                                    <li class="menu-item-row" style="padding: 10px; border-bottom: 1px solid #eee; margin-left: ${item.parent > 0 ? '40px' : '0'}">
                                        <div style="display: flex; justify-content: space-between; align-items: center;">
                                            <div>
                                                <strong>${item.title}</strong>
                                                <span style="background: #e7f3ff; color: #0073aa; padding: 2px 6px; border-radius: 4px; font-size: 0.75em; margin-left: 5px;">
                                                    ${item.type_label}
                                                </span>
                                            </div>
                                            <button class="edit-btn" data-id="${item.id}" data-title="${item.title}" data-url="${item.url}" 
                                                style="cursor: pointer; padding: 5px 10px;">ویرایش</button>
                                        </div>
                                        <div style="font-size: 0.85em; color: #555; margin-top: 5px; font-family: monospace;">
                                            URL: <a href="${item.url}" target="_blank">${item.url}</a>
                                        </div>
                                    </li>
                                `).join('')}
                            </ul>
                        </div>
                    `).join('')}
                </div>
            `;

            // ایونت لیسنر برای دکمه‌های ویرایش
            body.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', (e) => this.openEditModal(e.target.dataset));
            });

        } catch (err) {
            body.innerHTML = `<div style="color: red; padding: 20px;">خطا در دریافت لیست منوها: ${err.message}</div>`;
        }
        return this;
    }


    openEditModal(item) {
        const modalId = 'menu-edit-modal';
        document.body.insertAdjacentHTML('beforeend', `
            <div id="${modalId}" style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; display:flex; justify-content:center; align-items:center;">
                <div style="background:white; padding: 20px; border-radius: 8px; width: 400px; box-shadow: 0 2px 10px rgba(0,0,0,0.3);">
                    <h3>ویرایش: ${item.title}</h3>
                    <div style="margin-bottom: 10px;">
                        <label>عنوان:</label><br>
                        <input type="text" id="edit-title" value="${item.title}" style="width: 100%; padding: 8px;">
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label>URL:</label><br>
                        <input type="text" id="edit-url" value="${item.url}" style="width: 100%; padding: 8px;">
                    </div>
                    <button id="save-btn" style="padding: 8px 15px; cursor: pointer;">ذخیره</button>
                    <button id="close-btn" style="padding: 8px 15px; cursor: pointer; margin-right: 5px;">انصراف</button>
                </div>
            </div>
        `);

        document.getElementById('save-btn').onclick = () => {
            const newTitle = document.getElementById('edit-title').value;
            const newUrl = document.getElementById('edit-url').value;
            this.saveMenuItem(item.id, newTitle, newUrl);
        };

        document.getElementById('close-btn').onclick = () => document.getElementById(modalId).remove();
    }

    async saveMenuItem(id, title, url) {
        try {
            const response = await this.api.post("/wordpress/wp-menus/update", { menu_item_id: id, title, url });
            if (response.success) {
                alert("بروزرسانی با موفقیت انجام شد.");
                document.getElementById('menu-edit-modal').remove();
                this.render(this.container); // رندر مجدد
            }
        } catch (err) {
            alert("خطا در ذخیره: " + err.message);
        }
    }
}

viewRegistry.register("manager", WordpressView);
export default WordpressView;
