<template>
    <v-app>
        <template v-if="isAuthenticatedRoute">
            <!-- TOP BAR -->
            <v-app-bar elevation="1">
                <v-app-bar-nav-icon @click="drawer = !drawer" />
                <v-toolbar-title>RegcureFlow</v-toolbar-title>
                <v-spacer />
                <v-chip
                    color="secondary"
                    variant="tonal"
                    class="mr-3"
                    v-if="organization?.name"
                >
                    {{ organization.name }}
                </v-chip>

                <v-menu>
                    <template #activator="{ props }">
                        <v-btn v-bind="props" variant="text" class="text-none">
                            <v-icon start icon="mdi-account-circle" />
                            {{ currentUser?.displayName || currentUser?.email }}
                        </v-btn>
                    </template>

                    <v-list>
                        <v-list-item
                            :title="currentUser?.displayName || currentUser?.email"
                            :subtitle="currentUser?.email"
                        />
                        <v-list-item
                            prepend-icon="mdi-logout"
                            title="Logout"
                            @click="onLogout"
                        />
                    </v-list>
                </v-menu>
            </v-app-bar>

            <!-- SIDEBAR -->
            <v-navigation-drawer v-model="drawer" permanent>
                <v-list density="compact" nav>
                    <template v-for="(item, index) in filteredMenu" :key="index">

                        <!-- Divider -->
                        <v-divider
                            v-if="item.type === 'divider'"
                            class="my-2"
                        />

                        <!-- Single Item -->
                        <v-list-item
                            v-else-if="item.type === 'item'"
                            :prepend-icon="item.icon"
                            :to="buildRoute(item.route)"
                        >
                            <template #title>
                                {{ item.title }}
                            </template>
                        </v-list-item>
                        <!-- Group -->
                        <template v-else-if="item.type === 'group'">

                            <!-- Group Title -->
                            <v-list-subheader class="d-flex align-center text-uppercase font-weight-bold">
                                {{ item.title }}
                            </v-list-subheader>

                            <!-- Group Items -->
                            <v-list-item
                                v-for="(child, cIndex) in item.children"
                                :key="cIndex"
                                :to="buildRoute(child.route)"
                                class="pl-4"
                                :prepend-icon="child.icon"
                            >
                                <template #title>
                                    {{ child.title }}
                                </template>
                            </v-list-item>

                        </template>

                    </template>
                </v-list>
            </v-navigation-drawer>

            <!-- MAIN -->
            <v-main>
                <v-container fluid>
                    <router-view />
                </v-container>
            </v-main>
        </template>

        <!-- UNAUTH -->
        <template v-else>
            <v-main>
                <router-view />
            </v-main>
        </template>
    </v-app>
</template>

<script setup>
import axios from "axios"
import { computed, ref, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import { apiEndpoints } from "../apiEndpoints"
import { currentUser, logout } from "../auth"

const route = useRoute()
const router = useRouter()

const drawer = ref(true)
const organization = ref(null)

const sidebarMenu = [
    {
        type: "group",
        title: "Realtime",
        children: [
            { title: "My Work", route: "my-work", icon: "mdi-run" },
            { title: "Overview", icon: "mdi-view-dashboard", route: "dashboard", permission: "canAccessOverview" },
        ],
    },
    {
        type: "group",
        title: "Activity",
        children: [
            { title: "Activities", route: "activities", icon: "mdi-history" },
            { title: "Apps", route: "apps", icon: "mdi-apps" },
            { title: "Timeline", route: "timeline", icon: "mdi-chart-box" },
        ],
    },
    {
        type: "divider",
    },
    {
        type: "group",
        title: "Settings",
        permission: "canAccessSettings",
        children: [
            { title: "Manage Employees", route: "members", icon: "mdi-account-group", },
            { title: "Manage Company Details", route: "settings", icon: "mdi-cog" },
        ],
    },
];

/* ------------------ COMPUTED ------------------ */

const isAuthenticatedRoute = computed(() => route.path !== "/login")

const isOwner = computed(() =>
    Number(organization.value?.ownerId) === Number(currentUser.value?.id)
)

const canAccessSettings = computed(() => isOwner.value || Boolean(organization.value?.isAdmin))
const canAccessOverview = computed(() => isOwner.value  || Boolean(organization.value?.isAdmin) || Boolean(organization.value?.isManager))

/* ------------------ PERMISSION MAP ------------------ */

const permissionsMap = {
    canAccessSettings,
    canAccessOverview
}

/* ------------------ FILTER MENU ------------------ */

const filteredMenu = computed(() => {
    return sidebarMenu
        .map(item => {
            // Check group permission
            if (item.permission && !permissionsMap[item.permission]?.value) {
                return null
            }

            // Handle group
            if (item.type === "group") {
                const filteredChildren = item.children.filter(child => {
                    if (!child.permission) return true
                    return permissionsMap[child.permission]?.value
                })

                // Remove group if no visible children
                if (filteredChildren.length === 0) return null

                return {
                    ...item,
                    children: filteredChildren,
                }
            }

            // Normal item
            return item
        })
        .filter(Boolean)
})

/* ------------------ HELPERS ------------------ */

function buildRoute(name) {
    return {
        name,
        params: {
            organizationId: currentUser.value?.organizationId || '0',
        },
    }
}

/* ------------------ WATCH ------------------ */

watch(
    () => currentUser.value?.id,
    async () => {
        if (!currentUser.value) return
        try {
            const { data } = await axios.get(apiEndpoints.organizations.list, {
                params: { page: 1, perPage: 1 },
            })
            organization.value = data?.data?.[0] || null
        } catch {
            organization.value = null
        }
    },
    { immediate: true }
)

/* ------------------ ACTIONS ------------------ */

async function onLogout() {
    await logout()
    await router.push("/login")
}
</script>
