/**
 * CategoryManagement.js
 * Tabulator library based implementation
 */

// Global Table Instance
let categoryTable = null;
let categoryList = []; // Full flat list from server

// Category division map for labels
const categoryDivMap = {
    "01": "다이어트 시술",
    "02": "다이어트 이벤트",
    "03": "쁘띠 시술",
    "04": "쁘띠 이벤트",
    "05": "다이어트 전후사진",
    "06": "쁘띠 전후사진"
};

// Initialize
$(function () {
    fn_init();
    fn_initEvent();
});

function fn_init() {
    // Initial load
    fn_searchCategoryList();
}


function fn_initEvent() {
    // Expand/Collapse All (Groups)
    $("#btnExpandAll").click(function () {
        if (categoryTable) {
            console.log("Expanding all groups...");
            categoryTable.blockRedraw();
            categoryTable.getGroups().forEach(group => group.show());
            categoryTable.restoreRedraw();
        }
    });

    $("#btnCollapseAll").click(function () {
        if (categoryTable) {
            console.log("Collapsing all groups...");
            categoryTable.blockRedraw();
            categoryTable.getGroups().forEach(group => group.hide());
            categoryTable.restoreRedraw();
        }
    });

    // CRUD Buttons (Top)
    $("#btnInsertWebCategory").click(function () {
        fn_showInsertForm();
    });

    $("#btnDeleteWebCategory").click(function () {
        fn_deleteCategory();
    });

    // Form Buttons
    $("#btnSaveCategory").click(fn_insertCategory);
    $("#btnCancelInsert").click(fn_hideDetailPanel);

    $("#btnUpdateCategory").click(fn_updateCategory);
    $("#btnCancelEdit").click(fn_hideDetailPanel);
}

/**
 * Fetch Data
 */
function fn_searchCategoryList() {
    let formData = new FormData();
    formData.append("menuClass", menuClass);

    // Server expects gridLimitStart/End for pagination, sending large range for All data
    formData.append("gridLimitStart", 0);
    formData.append("gridLimitEnd", 100000);

    // Search filters (Removed)
    formData.append("searchCategoryDivCd", "");
    formData.append("searchCategoryNm", "");

    // Sort
    formData.append("gridSort", "CATEGORY_DIV_CD ASC, CATEGORY_NM ASC");

    $.ajax({
        url: encodeURI('/categoryManagement/getCategoryManagementList.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            if (data.msgCode === '0' || data.success === 'true') {
                categoryList = data.rows || [];
                fn_renderTable(categoryList);
                fn_hideDetailPanel();
            } else {
                alert(data.msgDesc || "조회 중 오류가 발생했습니다.");
            }
        },
        error: function () {
            alert("서버 통신 오류가 발생했습니다.");
        }
    });
}

// Render Tabulator
function fn_renderTable(list) {
    // Pre-process list to strip HTML tags for display if needed, 
    // or we can use a formatter. Let's use a simple formatter.

    categoryTable = new Tabulator("#categoryTreeContainer", {
        data: list,
        layout: "fitColumns",
        selectableRows: false, // Updated: Only select via checkbox
        groupBy: "categoryDivCd",
        groupStartOpen: true, // Default to Expanded
        groupHeader: function (value, count, data, group) {
            // Custom Header: "Division Name (Count)"
            let label = categoryDivMap[value] || value;
            return label + " (" + count + ")";
        },
        columns: [
            {
                formatter: "rowSelection",
                titleFormatter: "rowSelection",
                headerSort: false,
                width: 40,
                hozAlign: "center",
                headerHozAlign: "center",
                cellClick: function (e, cell) {
                    cell.getRow().toggleSelect();
                }
            },
            {
                title: "카테고리명",
                field: "categoryNm",
                headerSort: false,
                formatter: function (cell) {
                    // Strip HTML tags
                    let val = cell.getValue();
                    return val ? String(val).replace(/<[^>]*>?/gm, '') : '';
                },
                cellClick: function (e, cell) {
                    // Handle Cell Click -> Edit
                    const row = cell.getRow();
                    const item = row.getData();

                    // Highlight Row
                    if (categoryTable) {
                        const rows = categoryTable.getRows();
                        rows.forEach(r => r.getElement().classList.remove("row-active"));
                        row.getElement().classList.add("row-active");
                    }

                    console.log("Name Cell Clicked:", item);
                    fn_showEditForm(item);
                }
            }
        ],
        // rowClick was causing issues with selection/edit overlap. 
        // Moved to specific cellClick handlers.
    });
}


/**
 * Detail Panel: Hide All
 */
function fn_hideDetailPanel() {
    $("#categoryInsertForm").hide();
    $("#categoryEditForm").hide();
    $("#categoryDetailContent").show(); // Default empty state
    // Clear selection if desired
    // if(categoryTable) categoryTable.deselectRow(); // Optional: keep selection
}

/**
 * Detail Panel: Show Insert
 */
function fn_showInsertForm(preSelectDivCd) {
    if ("Y" !== insertUseYn) {
        alert("등록 권한이 없습니다.");
        return;
    }

    $("#categoryDetailContent").hide();
    $("#categoryEditForm").hide();
    $("#categoryInsertForm").show();

    // Reset fields
    $("#insertCategoryDivCd").val(preSelectDivCd || "");
    $("#insertCategoryNm").val("");
    // Order No is auto-generated (MAX+1) on server

    // Update Header
    $(".detail-panel-title").text("카테고리 등록");
}

/**
 * Detail Panel: Show Edit
 */
function fn_showEditForm(item) {
    if (!item) return;
    console.log("Show Edit Form for:", item);

    try {
        $("#categoryDetailContent").hide();
        $("#categoryInsertForm").hide();
        $("#categoryEditForm").show();

        // Fill fields
        $("#editCategoryNo").val(item.categoryNo); // PK
        $("#editCategoryDivCd").val(item.categoryDivCd); // PK part

        $("#editCategoryDivNm").val(categoryDivMap[item.categoryDivCd] || item.categoryDivCd);

        // Strip HTML for input value as well? usually we want the raw value if it is editable.
        // Assuming edit is for clean text.
        let cleanName = item.categoryNm ? String(item.categoryNm).replace(/<[^>]*>?/gm, '') : '';
        $("#editCategoryNm").val(cleanName);
        $("#editOrderNo").val(item.orderNo || "0"); // Set Order No

        $("#editRegDate").val(item.regDate);

        // Update Header
        $(".detail-panel-title").text("카테고리 상세/수정");
    } catch (err) {
        console.error("Error displaying edit form:", err);
    }
}

/**
 * Action: Insert
 */
function fn_insertCategory() {
    const divCd = $("#insertCategoryDivCd").val();
    const nm = $("#insertCategoryNm").val();
    // Order No handled by backend (MAX+1)

    if (!divCd) { alert("카테고리 구분을 선택해주세요."); return; }
    if (!nm) { alert("카테고리명을 입력해주세요."); return; }

    const data = {
        categoryDivCd: divCd,
        categoryNm: nm,
        orderNo: 0, // Default 0 to trigger backend logic
        menuClass: menuClass
    };

    $.ajax({
        url: '/categoryManagement/putCategoryManagement.do',
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (res) {
            let response = (typeof res === 'string') ? JSON.parse(res) : res;
            if (response.msgCode === '0') {
                alert("등록되었습니다.");
                fn_searchCategoryList(); // reload
            } else {
                alert(response.msgDesc);
            }
        },
        error: function () {
            alert("등록 중 오류가 발생했습니다.");
        }
    });
}

/**
 * Action: Update
 */
function fn_updateCategory() {
    if ("Y" !== updateUseYn) {
        alert("수정 권한이 없습니다.");
        return;
    }

    const no = $("#editCategoryNo").val();
    const divCd = $("#editCategoryDivCd").val();
    const nm = $("#editCategoryNm").val();
    const orderNo = $("#editOrderNo").val() || 0;

    if (!nm) { alert("카테고리명을 입력해주세요."); return; }

    const data = {
        categoryNo: no,
        categoryDivCd: divCd,
        categoryNm: nm,
        orderNo: orderNo,
        menuClass: menuClass
    };

    $.ajax({
        url: '/categoryManagement/modCategoryManagement.do',
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (res) {
            let response = (typeof res === 'string') ? JSON.parse(res) : res;
            if (response.msgCode === '0') {
                alert("수정되었습니다.");
                fn_searchCategoryList();
            } else {
                alert(response.msgDesc);
            }
        },
        error: function () {
            alert("수정 중 오류가 발생했습니다.");
        }
    });
}

/**
 * Action: Delete
 */
function fn_deleteCategory() {
    if ("Y" !== deleteUseYn) {
        alert("삭제 권한이 없습니다.");
        return;
    }

    if (!categoryTable) return;

    // Get Selected Data
    const selectedData = categoryTable.getSelectedData();

    if (selectedData.length === 0) {
        alert("삭제할 카테고리를 선택해주세요.");
        return;
    }

    // Map to required format
    const itemsToDelete = selectedData.map(item => ({
        categoryNo: item.categoryNo,
        categoryDivCd: item.categoryDivCd
    }));

    if (confirm(itemsToDelete.length + "건의 카테고리를 삭제하시겠습니까?")) {
        const data = {
            delList: itemsToDelete,
            menuClass: menuClass
        };

        $.ajax({
            url: '/categoryManagement/delCategoryManagement.do',
            data: JSON.stringify(data),
            contentType: 'application/json',
            type: 'POST',
            success: function (res) {
                let response = (typeof res === 'string') ? JSON.parse(res) : res;
                if (response.msgCode === '0') {
                    alert("삭제되었습니다.");
                    fn_searchCategoryList();
                } else {
                    alert(response.msgDesc);
                }
            },
            error: function () {
                alert("삭제 중 오류가 발생했습니다.");
            }
        });
    }
}