<template>
    <a-drawer
        :title="pageTitle"
        :width="drawerWidth"
        :open="visible"
        :body-style="{ paddingBottom: '80px' }"
        :footer-style="{ textAlign: 'right' }"
        :maskClosable="false"
        @close="onClose"
    >
        <a-form layout="vertical">
            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                    <a-form-item
                        :label="$t('role.display_name')"
                        name="display_name"
                        :help="rules.display_name ? rules.display_name.message : null"
                        :validateStatus="rules.display_name ? 'error' : null"
                        class="required"
                    >
                        <a-input
                            v-model:value="formData.display_name"
                            :placeholder="
                                $t('common.placeholder_default_text', [
                                    $t('role.display_name'),
                                ])
                            "
                            v-on:keyup="formData.name = slugify($event.target.value)"
                        />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                    <a-form-item
                        :label="$t('role.role_name')"
                        name="name"
                        :help="rules.name ? rules.name.message : null"
                        :validateStatus="rules.name ? 'error' : null"
                        class="required"
                    >
                        <a-input
                            v-model:value="formData.name"
                            :placeholder="
                                $t('common.placeholder_default_text', [
                                    $t('role.role_name'),
                                ])
                            "
                        />
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="24" :lg="24">
                    <a-form-item
                        :label="$t('role.description')"
                        name="description"
                        :help="rules.description ? rules.description.message : null"
                        :validateStatus="rules.description ? 'error' : null"
                    >
                        <a-textarea
                            v-model:value="formData.description"
                            :placeholder="
                                $t('common.placeholder_default_text', [
                                    $t('role.description'),
                                ])
                            "
                            :rows="4"
                        />
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="6">
                    <a-form-item :label="$t('role.select_module')">
                        <a-select
                            v-model:value="selectedModule"
                            show-search
                            :placeholder="$t('role.select_module')"
                            :style="{ width: '100%' }"
                            @change="moduleSelected"
                            allow-clear
                        >
                            <a-select-option
                                v-for="moduleName in availableModules"
                                :key="moduleName"
                                :value="moduleName"
                            >
                                {{ moduleName }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                    <a-form-item :label="$t('role.search_permissions')">
                        <a-input-search
                            v-model:value="searchedPermission"
                            allowClear
                            :placeholder="$t('role.search_permissions')"
                            style="width: 100%"
                            @change="onSearch"
                        />
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="24" :lg="24">
                    <a-form-item
                        :label="$t('role.permissions')"
                        name="permissions"
                        :help="rules.permissions ? rules.permissions.message : null"
                        :validateStatus="rules.permissions ? 'error' : null"
                    >
                        <div class="d-flex flex-column scroll-y">
                            <div class="tbl-responsive">
                                <a-checkbox-group v-model:value="checkedPermissions">
                                    <table
                                        id="myTable"
                                        class="table align-middle table-row-dashed row-gap"
                                    >
                                        <tbody class="text-gray-600 fw-bold">
                                            <!-- Common/Default Permissions (Shown when no module selected) -->
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.staff_members") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'staff_members_view'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.view") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'staff_members_create'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.add") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'staff_members_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'staff_members_delete'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.delete") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("role.assign_role") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'assign_role'
                                                                    ]
                                                                "
                                                            >
                                                                {{
                                                                    $t("role.assign_role")
                                                                }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>

                                            <!-- Dynamically imported permission components -->
                                            <component
                                                v-show="!selectedModule"
                                                v-for="(
                                                    permComponent, index
                                                ) in dynamicPermissionComponents"
                                                :key="index"
                                                :is="permComponent"
                                                :permissions="permissions"
                                            />

                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.company") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'companies_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>

                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.translations") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'translations_view'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.view") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'translations_create'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.add") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'translations_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'translations_delete'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.delete") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.roles") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'roles_view'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.view") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'roles_create'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.add") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'roles_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'roles_delete'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.delete") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.icon_sets") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'icon_sets_view'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.view") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'icon_sets_create'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.add") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'icon_sets_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'icon_sets_delete'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.delete") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.storage_settings") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'storage_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.email_settings") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'email_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.ai_settings") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'ai_settings_edit'
                                                                    ]
                                                                "
                                                            >
                                                                {{ $t("common.edit") }}
                                                            </a-checkbox>
                                                        </label>
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'ai_features_access'
                                                                    ]
                                                                "
                                                            >
                                                                {{
                                                                    $t(
                                                                        "ai_settings.features_access"
                                                                    )
                                                                }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr v-show="!selectedModule">
                                                <td class="text-gray-800">
                                                    {{ $t("menu.update_app") }}
                                                </td>
                                                <td>
                                                    <div class="d-flex">
                                                        <label
                                                            class="form-check form-check-custom me-5 me-lg-20"
                                                        >
                                                            <a-checkbox
                                                                :value="
                                                                    permissions[
                                                                        'update_app'
                                                                    ]
                                                                "
                                                            >
                                                                {{
                                                                    $t(
                                                                        "common.update_app"
                                                                    )
                                                                }}
                                                            </a-checkbox>
                                                        </label>
                                                    </div>
                                                </td>
                                            </tr>

                                            <!-- Module-Specific Permissions (When Module is Selected) -->
                                            <PermissionGroup
                                                v-show="selectedModule"
                                                :module-permissions="modulePermissions"
                                                :selected-module="selectedModule"
                                            />
                                        </tbody>
                                    </table>
                                </a-checkbox-group>
                            </div>
                        </div>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-button
                type="primary"
                @click="onSubmit"
                style="margin-right: 8px"
                :loading="loading"
            >
                <template #icon> <SaveOutlined /> </template>
                {{ addEditType == "add" ? $t("common.create") : $t("common.update") }}
            </a-button>
            <a-button @click="onClose">
                {{ $t("common.cancel") }}
            </a-button>
        </template>
    </a-drawer>
</template>
<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { PlusOutlined, LoadingOutlined, SaveOutlined } from "@ant-design/icons-vue";
import { useI18n } from "vue-i18n";
import PermissionGroup from "./PermissionGroup.vue";

// Dynamically import all permission.vue files from views folders
const permissionModules = import.meta.glob("../../**/permission.vue", { eager: true });
const dynamicPermissionComponents = Object.values(permissionModules)
    .map((module) => module.default)
    .sort((a, b) => {
        const orderA = a.order ?? 999;
        const orderB = b.order ?? 999;
        return orderA - orderB;
    });

const props = defineProps([
    "formData",
    "data",
    "visible",
    "url",
    "addEditType",
    "pageTitle",
    "successMessage",
]);

const emit = defineEmits(["addEditSuccess", "closed"]);

const { addEditRequestAdmin, loading, rules } = window.__composables.apiAdmin();
const roles = ref([]);
const { t } = useI18n();
const permissions = ref([]);
const checkedPermissions = ref([]);
const { slugify } = window.__composables.common();

const searchedPermission = ref("");
const selectedModule = ref(undefined);
const modulePermissions = ref([]);
const availableModules = computed(() => {
    return modulePermissions.value.map((module) => module.module_name);
});

const onSearch = () => {
    var input, filter, table, tr, td, i, txtValue;
    input = searchedPermission.value;
    filter = input.toUpperCase();

    if (document && document.getElementById("myTable")) {
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");

        if (filter) {
            // Search mode: apply filters
            for (i = 0; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td")[0];
                if (td) {
                    // First, remove any existing inline style to check v-show state
                    const hadInlineStyle = tr[i].style.display ? true : false;
                    if (hadInlineStyle) {
                        tr[i].style.removeProperty("display");
                    }

                    const computedDisplay = window.getComputedStyle(tr[i]).display;
                    txtValue = td.textContent || td.innerText;

                    // Only search within rows that would be visible (not hidden by v-show)
                    if (computedDisplay !== "none") {
                        if (txtValue.toUpperCase().indexOf(filter) > -1) {
                            // Row matches - ensure it's visible
                            if (tr[i].style.display === "none") {
                                tr[i].style.removeProperty("display");
                            }
                        } else {
                            // Row doesn't match - hide it
                            tr[i].style.display = "none";
                        }
                    } else {
                        // Row is hidden by v-show - don't touch it
                        // But restore inline style if it had one before
                        if (hadInlineStyle) {
                            tr[i].style.display = "none";
                        }
                    }
                }
            }
        } else {
            // No search term - remove ALL inline styles and let v-show control visibility
            for (i = 0; i < tr.length; i++) {
                if (tr[i].style.display) {
                    tr[i].style.removeProperty("display");
                }
            }
        }
    }
};

onMounted(() => {
    // Fetch module-wise permissions from new endpoint
    axiosAdmin.get("module-wise-permissions").then((response) => {
        modulePermissions.value = response.data.permissions;
    });

    // Keep old permissions endpoint for backward compatibility with dynamic components
    axiosAdmin.get("permissions").then((response) => {
        const permissionArray = [];
        response.data.map((res) => {
            permissionArray[res.name] = res.xid;
        });
        permissions.value = permissionArray;
    });
});

const moduleSelected = () => {
    // Trigger search to update visible rows
    onSearch();
};

const onSubmit = () => {
    const newFormData = {
        ...props.formData,
        permissions: checkedPermissions.value,
    };

    addEditRequestAdmin({
        url: props.url,
        data: newFormData,
        successMessage: props.successMessage,
        success: (res) => {
            emit("addEditSuccess", res.xid);
        },
    });
};

const onClose = () => {
    rules.value = {};
    selectedModule.value = undefined;
    emit("closed");
};

watch(
    () => props.visible,
    (newVal, oldVal) => {
        if (newVal) {
            searchedPermission.value = "";
            onSearch();
        }

        if (newVal && props.addEditType == "edit") {
            props.data.perms.forEach((value) => {
                checkedPermissions.value.push(value.xid);
            });
        } else {
            checkedPermissions.value = [];
        }
    }
);

// Watch for search term changes
watch(searchedPermission, () => {
    onSearch();
});

const drawerWidth = window.innerWidth <= 991 ? "90%" : "45%";
</script>

<style lang="less">
.flex-column {
    flex-direction: column !important;
}

.d-flex {
    display: flex !important;
}

.tbl-responsive {
    overflow-x: auto;
}

.table {
    width: 100%;
}

.align-middle {
    vertical-align: middle !important;
}
.table > tbody {
    vertical-align: inherit;
}
.text-gray-600 {
    color: #7e8299 !important;
}
.fw-bold {
    font-weight: 500 !important;
}
tbody,
td,
tfoot,
th,
thead,
tr {
    border-color: inherit;
    border-style: solid;
    border-width: 0;
}

.table.table-row-dashed tr {
    border-bottom-width: 1px;
    border-bottom-style: dashed;
    border-bottom-color: #eff2f5;
}

.table td:first-child,
.table th:first-child,
.table tr:first-child {
    padding-left: 0;
}

.form-check.form-check-custom {
    display: flex;
    align-items: center;
    padding-left: 0;
    margin: 0;
}

.me-9 {
    margin-right: 2.25rem !important;
}

.table.row-gap td,
.table.row-gap th {
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
}

.me-lg-20 {
    margin-right: 5rem !important;
}

.ant-checkbox-group {
    width: 100%;
}
</style>
