<template>
    <div>
        <div v-if="loading" class="row">
            <div class="col-12 tx-semibold text-center text-default">
                <span class="spinner-border spinner-border-sm"></span>
            </div>
        </div>
        <form v-if="!loading" @submit.prevent="onSave">
            <div class="row">
                <!-- Cột trái: Danh sách quyền theo nhóm -->
                <div class="col-md-6 border-end pe-3" style="max-height: 480px; overflow-y: auto;">
                    <input v-model="search" placeholder="Tìm kiếm quyền..." class="form-control mb-2" />
                    <div class="d-flex justify-content-end mb-2" v-if="Object.keys(filteredGroupedRoles).length > 1">
                        <button type="button" class="btn btn-xs btn-outline-secondary me-1"
                            @click="expandAllLeft">Expand All</button>
                        <button type="button" class="btn btn-xs btn-outline-secondary" @click="collapseAllLeft">Collapse
                            All</button>
                    </div>
                    <div v-for="(groupRoles, group) in filteredGroupedRoles" :key="group" class="mb-3">
                        <div class="d-flex align-items-center mb-1 group-header" @click="toggleCollapseLeft(group)">
                            <span class="me-2" style="cursor:pointer;user-select:none;">
                                <span v-if="!collapsedLeft[group]">▼</span>
                                <span v-else>▶</span>
                            </span>
                            <input type="checkbox" :checked="isGroupChecked(groupRoles)"
                                :indeterminate="isGroupIndeterminate(groupRoles)"
                                @change.stop="toggleGroup(groupRoles, $event.target.checked)" class="me-2"
                                style="margin-top:2px" />
                            <b>{{ group }}</b>
                            <span class="ms-2 text-muted small">({{ groupRoles.length }})</span>
                        </div>
                        <div class="ps-4" v-show="!collapsedLeft[group]">
                            <div v-for="role in groupRoles" :key="role.Id" class="mb-1">
                                <label class="d-flex align-items-start">
                                    <input type="checkbox" v-model="selectedRoles" :value="role.Id" class="me-2 mt-1" />
                                    <div>
                                        <div class="fw-bold">{{ role.Name }}</div>
                                        <div class="text-muted small">{{ role.Description }}</div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Cột phải: Danh sách quyền đã chọn, nhóm theo controller nếu có -->
                <div class="col-md-6 ps-3" style="max-height: 480px; overflow-y: auto;">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <b>Quyền đã chọn ({{ selectedRoles.length }})</b>
                        <button v-if="selectedRoles.length" type="button" class="btn btn-sm btn-link text-danger"
                            @click="clearAll">Bỏ chọn tất cả</button>
                    </div>
                    <div class="d-flex justify-content-end mb-2" v-if="Object.keys(selectedGroupedRoles).length > 1">
                        <button type="button" class="btn btn-xs btn-outline-secondary me-1"
                            @click="expandAllRight">Expand All</button>
                        <button type="button" class="btn btn-xs btn-outline-secondary"
                            @click="collapseAllRight">Collapse All</button>
                    </div>
                    <div v-if="selectedRoles.length === 0" class="text-muted small">Chưa chọn quyền nào.</div>
                    <template v-if="Object.keys(selectedGroupedRoles).length > 1">
                        <div v-for="(groupRoles, group) in selectedGroupedRoles" :key="group" class="mb-2">
                            <div class="d-flex align-items-center group-header mb-1"
                                @click="toggleCollapseRight(group)">
                                <span class="me-2" style="cursor:pointer;user-select:none;">
                                    <span v-if="!collapsedRight[group]">▼</span>
                                    <span v-else>▶</span>
                                </span>
                                <b>{{ group }}</b>
                                <span class="ms-2 text-muted small">({{ groupRoles.length }})</span>
                            </div>
                            <div v-show="!collapsedRight[group]">
                                <div v-for="role in groupRoles" :key="role.Id"
                                    class="mb-2 border-bottom pb-1 d-flex justify-content-between align-items-center">
                                    <div>
                                        <b>{{ role.Name }}</b>
                                        <span class="text-muted small ms-2">{{ role.Description }}</span>
                                    </div>
                                    <button type="button" class="btn btn-xs btn-outline-danger"
                                        @click="removeRole(role.Id)">Bỏ chọn</button>
                                </div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <div>
                            <div v-for="role in selectedRoleObjects" :key="role.Id"
                                class="mb-2 border-bottom pb-1 d-flex justify-content-between align-items-center">
                                <div>
                                    <b>{{ role.Name }}</b>
                                    <span class="text-muted small ms-2">{{ role.Description }}</span>
                                </div>
                                <button type="button" class="btn btn-xs btn-outline-danger"
                                    @click="removeRole(role.Id)">Bỏ chọn</button>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
            <div class="mt-3 d-flex flex-row-reverse">
                <button type="button" class="btn btn-main-default mg-l-15" @click="cancel">Bỏ qua</button>
                <button type="submit" class="btn btn-main-primary">Lưu</button>
            </div>
        </form>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import roleService from '@/services/roleService';
import permissionService from '@/services/permissionService';
import { useToast } from "vue-toastification";
const toast = useToast();

const props = defineProps({
    permission: Object
});
const emit = defineEmits(['close']);

const roles = ref([]);
const selectedRoles = ref([]);
const loading = ref(false);
const search = ref('');

// Collapse state for left and right columns
const collapsedLeft = ref({});
const collapsedRight = ref({});

onMounted(async () => {
    loading.value = true;
    roles.value = await roleService.getList();
    const assigned = await permissionService.getRoles(props.permission.id || props.permission.Id);
    selectedRoles.value = assigned.map(r => r.Id);
    // Mặc định tất cả nhóm đều expand khi mở dialog
    setDefaultCollapse();
    loading.value = false;
});

function setDefaultCollapse() {
    // Left
    Object.keys(groupedRoles.value).forEach(group => {
        collapsedLeft.value[group] = false;
    });
    // Right
    Object.keys(selectedGroupedRoles.value).forEach(group => {
        collapsedRight.value[group] = false;
    });
}

// Collapse/Expand all left
function collapseAllLeft() {
    Object.keys(filteredGroupedRoles.value).forEach(group => {
        collapsedLeft.value[group] = true;
    });
}
function expandAllLeft() {
    Object.keys(filteredGroupedRoles.value).forEach(group => {
        collapsedLeft.value[group] = false;
    });
}
// Collapse/Expand all right
function collapseAllRight() {
    Object.keys(selectedGroupedRoles.value).forEach(group => {
        collapsedRight.value[group] = true;
    });
}
function expandAllRight() {
    Object.keys(selectedGroupedRoles.value).forEach(group => {
        collapsedRight.value[group] = false;
    });
}

// Gom nhóm quyền theo controller (tiền tố trước dấu chấm)
const groupedRoles = computed(() => {
    const groups = {};
    roles.value.forEach(role => {
        const prefix = role.Name.split('.')[0] || 'Khác';
        if (!groups[prefix]) groups[prefix] = [];
        groups[prefix].push(role);
    });
    return groups;
});

// Lọc nhóm quyền theo từ khóa tìm kiếm và chỉ lấy quyền chưa được chọn
const filteredGroupedRoles = computed(() => {
    const keyword = search.value.trim().toLowerCase();
    const result = {};
    for (const group in groupedRoles.value) {
        // Chỉ lấy quyền chưa được chọn
        const filtered = groupedRoles.value[group].filter(role =>
            !selectedRoles.value.includes(role.Id) &&
            (role.Name.toLowerCase().includes(keyword) ||
                (role.Description && role.Description.toLowerCase().includes(keyword)))
        );
        if (filtered.length) result[group] = filtered;
    }
    return result;
});

// Danh sách object quyền đã chọn (theo thứ tự chọn)
const selectedRoleObjects = computed(() => {
    return roles.value.filter(r => selectedRoles.value.includes(r.Id));
});
// Nhóm quyền đã chọn theo controller
const selectedGroupedRoles = computed(() => {
    const groups = {};
    selectedRoleObjects.value.forEach(role => {
        const prefix = role.Name.split('.')[0] || 'Khác';
        if (!groups[prefix]) groups[prefix] = [];
        groups[prefix].push(role);
    });
    return groups;
});

// Chọn/bỏ chọn tất cả quyền trong một nhóm
function toggleGroup(groupRoles, checked) {
    const ids = groupRoles.map(r => r.Id);
    if (checked) {
        selectedRoles.value = Array.from(new Set([...selectedRoles.value, ...ids]));
    } else {
        selectedRoles.value = selectedRoles.value.filter(id => !ids.includes(id));
    }
}
// Kiểm tra trạng thái checkbox nhóm
function isGroupChecked(groupRoles) {
    return groupRoles.every(r => selectedRoles.value.includes(r.Id));
}
function isGroupIndeterminate(groupRoles) {
    const checked = groupRoles.filter(r => selectedRoles.value.includes(r.Id)).length;
    return checked > 0 && checked < groupRoles.length;
}
// Bỏ chọn 1 quyền ở cột phải
function removeRole(id) {
    selectedRoles.value = selectedRoles.value.filter(rid => rid !== id);
}
// Bỏ chọn tất cả
function clearAll() {
    selectedRoles.value = [];
}
// Collapse/Expand nhóm bên trái
function toggleCollapseLeft(group) {
    collapsedLeft.value[group] = !collapsedLeft.value[group];
}
// Collapse/Expand nhóm bên phải
function toggleCollapseRight(group) {
    collapsedRight.value[group] = !collapsedRight.value[group];
}

// KHÔNG còn watch([groupedRoles, selectedGroupedRoles], setDefaultCollapse);

async function onSave() {
    const model = {
        Id: props.permission.id || props.permission.Id,
        RoleIds: selectedRoles.value
    };
    await permissionService.updateRoles(model);
    toast.success('Cập nhật quyền thành công!');
    emit('close');
}

function cancel() {
    emit('close');
}
</script>

<style scoped>
.row {
    margin: 0;
}

.col-md-6 {
    min-width: 320px;
}

.group-header {
    cursor: pointer;
    user-select: none;
}

input[type="checkbox"]:indeterminate {
    background-color: #ffe082;
    border-color: #ffc107;
}
</style>