import { Grid } from "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js";
import GlobalConfig from "../global-config";

class Menus {
    constructor() {
        this.table = null;
    }
    init() {
        this.initTableMenus();
    }

    initTableMenus() {
        let tableContainer = document.getElementById("table-menus");

        if (this.table) {
            // If table exists, update its data instead of recreating
            this.table
                .updateConfig({
                    server: {
                        url: `${GlobalConfig.apiHost}/api/api-menus`,
                        credentials: "include",
                        headers: {
                            Authorization: `Bearer ${document
                                .querySelector('meta[name="api-token"]')
                                .getAttribute("content")}`,
                            "Content-Type": "application/json",
                        },
                        then: (data) =>
                            data.data.map((item) => [
                                item.id,
                                item.name,
                                item.url,
                                item.icon,
                                item.parent_id,
                                item.sort_order,
                                item.id,
                            ]),
                        total: (data) => data.total,
                    },
                })
                .forceRender();
            return;
        }

        this.table = new Grid({
            columns: [
                "ID",
                "Name",
                "Url",
                "Icon",
                "ParentID",
                "Sort Order",
                {
                    name: "Action",
                    formatter: (cell) =>
                        gridjs.html(`
                      <div class="d-flex justify-content-end gap-x-2">
                      <a href="/menus/${cell}/edit" class="btn btn-yellow me-2">Update</a>
                      <button class="btn btn-red btn-delete btn-delete-menu" data-id="${cell}">Delete</button>
                      `),
                },
            ],
            pagination: {
                limit: 15,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            search: {
                server: {
                    url: (prev, keyword) => `${prev}?search=${keyword}`,
                },
            },
            server: {
                url: `${GlobalConfig.apiHost}/api/api-menus`,
                credentials: "include",
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (data) =>
                    data.data.map((item) => [
                        item.id,
                        item.name,
                        item.url,
                        item.icon,
                        item.parent_id,
                        item.sort_order,
                        item.id,
                    ]),
                total: (data) => data.total,
            },
        }).render(tableContainer);

        document.addEventListener("click", this.handleDelete.bind(this));
    }

    handleDelete(event) {
        if (event.target.classList.contains("btn-delete-menu")) {
            event.preventDefault();
            const id = event.target.getAttribute("data-id");
            let modalElement = document.getElementById("modalConfirmation");
            let toastMessage = document.getElementById("toast-message");

            if (!modalElement) {
                console.error("Modal element not found!");
                return;
            }

            let modal = new bootstrap.Modal(modalElement);
            let btnSaveConfirmation = document.getElementById(
                "btnSaveConfirmation"
            );
            let toastElement = document.getElementById("toastNotification");
            let toast = new bootstrap.Toast(toastElement);

            // Remove previous event listeners to avoid multiple bindings
            btnSaveConfirmation.replaceWith(
                btnSaveConfirmation.cloneNode(true)
            );
            btnSaveConfirmation = document.getElementById(
                "btnSaveConfirmation"
            );

            // Set the role ID on the confirm button inside the modal
            btnSaveConfirmation.setAttribute("data-menu-id", id);

            // Show the modal
            modal.show();

            btnSaveConfirmation.addEventListener("click", async () => {
                let menuId = btnSaveConfirmation.getAttribute("data-menu-id");

                try {
                    let response = await fetch(`/menus/${menuId}`, {
                        method: "DELETE",
                        credentials: "include",
                        headers: {
                            "X-CSRF-TOKEN": document
                                .querySelector('meta[name="csrf-token"]')
                                .getAttribute("content"),
                            "Content-Type": "application/json",
                        },
                    });

                    if (response.ok) {
                        let result = await response.json();
                        toastMessage.innerText =
                            result.message || "Deleted successfully!";
                        toast.show();

                        // Hide modal
                        modal.hide();

                        // Refresh Grid.js table
                        this.refreshTableMenus();
                    } else {
                        let error = await response.json();
                        console.error("Delete failed:", error);
                        toastMessage.innerText =
                            error.message || "Delete failed!";
                        toast.show();
                    }
                } catch (error) {
                    console.error("Error deleting item:", error);
                    toastMessage.innerText = "An error occurred!";
                    toast.show();
                }
            });
        }
    }

    refreshTableMenus() {
        if (this.table) {
            this.table
                .updateConfig({
                    server: {
                        url: `${GlobalConfig.apiHost}/api/api-menus`,
                        credentials: "include",
                        headers: {
                            Authorization: `Bearer ${document
                                .querySelector('meta[name="api-token"]')
                                .getAttribute("content")}`,
                            "Content-Type": "application/json",
                        },
                        then: (data) =>
                            data.data.map((item) => [
                                item.id,
                                item.name,
                                item.url,
                                item.icon,
                                item.parent_id,
                                item.sort_order,
                                item.id,
                            ]),
                        total: (data) => data.total,
                    },
                })
                .forceRender();
        } else {
            this.initTableMenus(); // If no table exists, reinitialize it
        }
    }
}

document.addEventListener("DOMContentLoaded", function (e) {
    new Menus().init();
});
