import BaseView from "../../core/BaseView.js";

import {
    Tabulator,
    EditModule,
    SortModule,
    FilterModule,
    PageModule,
    SelectRowModule,
    AjaxModule,
    FormatModule,
    InteractionModule
} from "/wp-content/plugins/acc-engine/tabulator-master/dist/js/tabulator_esm.js";

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

Tabulator.registerModule([
    EditModule,
    SortModule,
    FilterModule,
    PageModule,
    SelectRowModule,
    AjaxModule,
    FormatModule,
    InteractionModule
]);

class UsersListView extends BaseView {

    static title = "Users";

    constructor(props = {}) {
        super(props);

        this.api = props.api;
        this.table = null;

        this._stylesInjected = false;

        // برای مدیریت مودال ویرایش
        this.editModalElement = null;
        this.currentEditingUser = null;
        this.currentEditingRow = null;
    }

    async render(container) {
        await super.render(container);

        const body = this.ref("body");

        body.innerHTML = `
            <div class="users-wrapper">

                <div class="users-toolbar">
                    <button class="btn-add">Add</button>
                    <button class="btn-delete">Delete</button>
                    <button class="btn-refresh">Refresh</button>
                    <input class="users-search" type="text" placeholder="Search...">
                </div>

                <div class="users-table users-cards-container"></div>

            </div>
        `;

        // ایجاد مودال ویرایش (یک بار)
        this._ensureEditModal(body);

        this.initTable();
        this.bindEvents();

        return this;
    }

    // --------- جدول کاربران --------- //

    initTable() {
        const tableEl = this.ref("body").querySelector(".users-table");

        const isMobile = window.matchMedia("(max-width: 768px)").matches;

        this.table = new Tabulator(tableEl, {
            height: isMobile ? undefined : 520,
            layout: "fitData",
            headerVisible: false,

            pagination: true,
            paginationMode: "remote",
            paginationSize: 10,

            ajaxURL: "/users",

            ajaxRequestFunc: async (url, config, params) => {
                const page = params.page || 1;
                const size = params.size || 10;
                const search = params.search || "";

                if (!this.api || typeof this.api.get !== "function") {
                    console.error("UsersListView: api client is missing or invalid", this.api);
                    throw new Error("ApiClient is not available in UsersListView");
                }

                const response = await this.api.get("users", {
                    page,
                    size,
                    search,
                });

                return {
                    data: Array.isArray(response.data) ? response.data : [],
                    last_page: response.last_page ?? 1,
                };
            },

            ajaxParams: { size: 10 },
            selectableRows: 1,

            columns: [
                { title: "ID", field: "id", sorter: "number", visible: false },
                { title: "Username", field: "username", editor: "input" },
                { title: "Full Name", field: "fullname", editor: "input" },
                { title: "Email", field: "email", editor: "input" },
                { title: "Roles", field: "roles" },
                {
                    title: "Delete",
                    field: "delete",
                    formatter: () => "🗑",
                    width: 80,
                    hozAlign: "center",
                    visible: false
                }
            ],

            rowFormatter: (row) => {
                const data = row.getData();
                const element = row.getElement();

                element.innerHTML = "";
                element.classList.add("user-card-row");

                const roles = Array.isArray(data.roles)
                    ? data.roles
                        .map(r => (typeof r === "string" ? r : r.name || ""))
                        .filter(Boolean)
                    : [];

                const rolesText = roles.length ? roles.join(", ") : "No roles";

                const card = document.createElement("div");
                card.className = "user-card";

                card.innerHTML = `
                    <div class="user-card-header">
                        <div class="user-card-avatar">
                            ${data.fullname ? data.fullname.charAt(0).toUpperCase() : "U"}
                        </div>
                        <div class="user-card-title">
                            <div class="user-card-fullname">${data.fullname || "(no name)"}</div>
                            <div class="user-card-username">@${data.username || ""}</div>
                        </div>
                    </div>

                    <div class="user-card-body">
                        <div class="user-card-row-item">
                            <span class="label">Email:</span>
                            <span class="value">${data.email || "-"}</span>
                        </div>
                        <div class="user-card-row-item">
                            <span class="label">Roles:</span>
                            <span class="value">${rolesText}</span>
                        </div>
                    </div>

                    <div class="user-card-footer">
                        <button type="button" class="btn-card-edit">Edit</button>
                        <button type="button" class="btn-card-delete">Delete</button>
                    </div>
                `;

                const btnEdit = card.querySelector(".btn-card-edit");
                const btnDelete = card.querySelector(".btn-card-delete");

                if (btnEdit) {
                    btnEdit.addEventListener("click", () => {
                        console.log("Edit user:", data);
                        this._openEditModal(data, row);
                    });
                }

                if (btnDelete) {
                    btnDelete.addEventListener("click", () => {
                        if (confirm(`Delete user ${data.username}?`)) {
                            // TODO: در صورت نیاز API DELETE را هم فراخوانی کن
                            // await this.api.request("DELETE", `users/${data.id}`);
                            row.delete();
                        }
                    });
                }

                element.appendChild(card);
            },

            cellEdited: (cell) => {
                const rowData = cell.getRow().getData();
                console.log("updated", rowData);
                // در صورت نیاز، اینجا هم می‌توانی inline-save به API انجام دهی
                // this.api.request("PUT", `users/${rowData.id}`, rowData);
            }
        });
    }

    // --------- نوار ابزار و رویدادهای کلی --------- //

    bindEvents() {
        const body = this.ref("body");
        const btnAdd = body.querySelector(".btn-add");
        const btnDelete = body.querySelector(".btn-delete");
        const btnRefresh = body.querySelector(".btn-refresh");
        const inputSearch = body.querySelector(".users-search");

        btnAdd?.addEventListener("click", () => {
            const user = {
                id: Date.now(),
                username: "new_user",
                fullname: "New User",
                email: "test@email.com",
                roles: []
            };
            this.table.addRow(user, true);
        });

        btnDelete?.addEventListener("click", () => {
            const row = this.table.getSelectedRows()[0];
            if (!row) {
                alert("Select a user");
                return;
            }
            const data = row.getData();
            if (confirm(`Delete selected user ${data.username}?`)) {
                // TODO: در صورت نیاز API DELETE
                // await this.api.request("DELETE", `users/${data.id}`);
                row.delete();
            }
        });

        btnRefresh?.addEventListener("click", () => {
            this.table.replaceData();
        });

        inputSearch?.addEventListener("input", (e) => {
            const value = e.target.value || "";
            this.table.setData(null, { search: value });
        });
    }

    // --------- مودال ویرایش کاربر --------- //

    /**
     * یک بار مودال را می‌سازد و به بدنه view اضافه می‌کند.
     */
    _ensureEditModal(container) {
        if (this.editModalElement) {
            return;
        }

        const modal = document.createElement("div");
        modal.className = "user-edit-modal-backdrop";
        modal.innerHTML = `
            <div class="user-edit-modal">
                <div class="user-edit-modal-header">
                    <h3>Edit User</h3>
                    <button type="button" class="user-edit-modal-close">&times;</button>
                </div>
                <div class="user-edit-modal-body">
                    <form class="user-edit-form">
                        <div class="form-group">
                            <label>Username</label>
                            <input name="username" type="text" class="form-control" />
                        </div>
                        <div class="form-group">
                            <label>Full Name</label>
                            <input name="fullname" type="text" class="form-control" />
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input name="email" type="email" class="form-control" />
                        </div>
                        <!-- در صورت نیاز، فیلد نقش‌ها یا موارد دیگر را هم اضافه کن -->

                        <div class="user-edit-modal-footer">
                            <button type="button" class="btn btn-secondary user-edit-cancel">Cancel</button>
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        container.appendChild(modal);
        this.editModalElement = modal;

        this._bindEditModalEvents();
        this._injectEditModalStyles();
    }

    _bindEditModalEvents() {
        const modal = this.editModalElement;
        if (!modal) return;

        const form = modal.querySelector(".user-edit-form");
        const btnClose = modal.querySelector(".user-edit-modal-close");
        const btnCancel = modal.querySelector(".user-edit-cancel");

        btnClose?.addEventListener("click", () => this._closeEditModal());
        btnCancel?.addEventListener("click", () => this._closeEditModal());

        form?.addEventListener("submit", async (event) => {
            event.preventDefault();

            if (!this.currentEditingRow || !this.currentEditingUser) {
                console.warn("No current editing user/row");
                return;
            }

            const formData = new FormData(form);

            const updatedUser = {
                ...this.currentEditingUser,
                username: formData.get("username"),
                fullname: formData.get("fullname"),
                email: formData.get("email"),
                // اگر فیلدهای دیگر (مثلاً roles) دارید اینجا جمع کنید
            };

            try {
                if (!this.api) {
                    throw new Error("ApiClient not available");
                }

                // فرض: PUT /users/{id}
                await this.api.request("PUT", `users/${this.currentEditingUser.id}`, updatedUser);

                // به‌روزرسانی UI
                this.currentEditingRow.update(updatedUser);

                this._closeEditModal();

            } catch (err) {
                console.error("Failed to update user", err);
                alert("Failed to update user");
            }
        });
    }

    _openEditModal(user, row) {
        this.currentEditingUser = user;
        this.currentEditingRow = row;

        const modal = this.editModalElement;
        if (!modal) return;

        const form = modal.querySelector(".user-edit-form");
        if (!form) return;

        form.elements["username"].value = user.username || "";
        form.elements["fullname"].value = user.fullname || "";
        form.elements["email"].value = user.email || "";

        modal.classList.add("is-open");
    }

    _closeEditModal() {
        const modal = this.editModalElement;
        if (!modal) return;

        modal.classList.remove("is-open");
        this.currentEditingUser = null;
        this.currentEditingRow = null;
    }

    /**
     * استایل‌های پایه برای مودال (اگر فریم‌ورک CSS دیگری ندارید)
     */
    _injectEditModalStyles() {
        if (this._stylesInjected) return;

        const style = document.createElement("style");
        style.textContent = `
            .user-edit-modal-backdrop {
                position: fixed;
                inset: 0;
                background: rgba(0, 0, 0, 0.4);
                display: none;
                align-items: center;
                justify-content: center;
                z-index: 9999;
            }

            .user-edit-modal-backdrop.is-open {
                display: flex;
            }

            .user-edit-modal {
                background: #fff;
                padding: 16px 20px;
                border-radius: 6px;
                min-width: 320px;
                max-width: 480px;
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            }

            .user-edit-modal-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10px;
            }

            .user-edit-modal-header h3 {
                margin: 0;
                font-size: 18px;
            }

            .user-edit-modal-close {
                border: none;
                background: transparent;
                font-size: 20px;
                cursor: pointer;
            }

            .user-edit-modal-body .form-group {
                margin-bottom: 10px;
            }

            .user-edit-modal-body label {
                display: block;
                margin-bottom: 4px;
                font-size: 13px;
                font-weight: 600;
            }

            .user-edit-modal-body .form-control {
                width: 100%;
                box-sizing: border-box;
                padding: 6px 8px;
                border-radius: 4px;
                border: 1px solid #ccc;
                font-size: 13px;
            }

            .user-edit-modal-footer {
                display: flex;
                justify-content: flex-end;
                gap: 8px;
                margin-top: 12px;
            }

            .user-edit-modal-footer .btn {
                padding: 6px 12px;
                font-size: 13px;
                cursor: pointer;
                border-radius: 4px;
                border: 1px solid transparent;
            }

            .user-edit-modal-footer .btn-primary {
                background-color: #007bff;
                border-color: #007bff;
                color: #fff;
            }

            .user-edit-modal-footer .btn-secondary {
                background-color: #f0f0f0;
                border-color: #ccc;
                color: #333;
            }
        `;
        document.head.appendChild(style);

        this._stylesInjected = true;
    }

    // --------- lifecycle --------- //

    destroy() {
        this.table?.destroy();
        this.table = null;

        if (this.editModalElement?.parentNode) {
            this.editModalElement.parentNode.removeChild(this.editModalElement);
        }
        this.editModalElement = null;
        this.currentEditingUser = null;
        this.currentEditingRow = null;

        super.destroy();
    }
}

export default UsersListView;

viewRegistry.register("users", UsersListView);
