<script>
import Swal from 'sweetalert2'
import axios from 'axios'
import { mapGetters, mapActions } from 'vuex'

export default {
    data() {
        return {
            userName: '',
            userRole: '',
            offices: [], // List of offices
        }
    },
    computed: {
        ...mapGetters(['user', 'authToken', 'refreshToken']),
        filteredOffices() {
            if (!this.user || !this.user.office_id) return [];

            // Jika user.id === 1 (Superadmin) atau user.id === 2, tampilkan semua kantor
            if (this.user.id === 1 || this.user.id === 2) {
                return this.offices;
            }

            // Jika bukan, hanya tampilkan kantor sesuai office_id user
            return this.offices.filter(office => office.id === this.user.office_id);
        }
    },

    methods: {
        ...mapActions(['logout', 'confirmLogout', 'setRefreshToken']),
        async fetchOffices() {
            try {
                const { data } = await axios.get('/api/offices/list', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                this.offices = data.data || [];
            } catch (error) {
                this.showErrorAlert('Error fetching office data!');
                console.error('Error fetching offices:', error);
                if (error.response?.status === 401) {
                    await this.handleTokenRefresh();
                    this.fetchOffices();
                }
            }
        },
        async confirmLogout() {
            try {
                const result = await Swal.fire({
                    title: 'Apakah Anda ingin logout?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ya, logout',
                    cancelButtonText: 'Batal'
                })

                if (result.isConfirmed) {
                    await axios.post(
                        '/api/logout',
                        {},
                        {
                            headers: {
                                Authorization: `Bearer ${this.authToken}`
                            }
                        }
                    )

                    this.logout()
                    this.clearSession()
                    this.showSuccessAlert('Logout Successfully !')
                    this.$router.push({ name: 'Login' })
                }
            } catch (error) {
                this.showErrorAlert(error.response?.data?.error || 'Terjadi kesalahan !')
            }
        },
        clearSession() {
            localStorage.removeItem('authToken')
            sessionStorage.removeItem('authToken')
            localStorage.removeItem('refreshToken')
            sessionStorage.removeItem('refreshToken')
            localStorage.removeItem('user')
            sessionStorage.removeItem('user')
        },
        setupAxiosInterceptors() {
            axios.interceptors.response.use(
                response => response,
                async error => {
                    const { config, response: { status } } = error
                    if (status === 401 && !config._retry) {
                        config._retry = true
                        const newToken = await this.refreshAuthToken()
                        if (newToken) {
                            config.headers['Authorization'] = `Bearer ${newToken}`
                            return axios(config)
                        }
                    }
                    return Promise.reject(error)
                }
            )
        },
        async refreshAuthToken() {
            try {
                const refresh_token = this.refreshToken
                const response = await axios.post('/api/refresh-token', { token: refresh_token })
                const { token, refresh_token: new_refresh_token } = response.data
                this.setAuthToken(token)
                this.setRefreshToken(new_refresh_token)
                this.setAxiosDefaults(token)
                return token
            } catch (error) {
                this.logout()
            }
        },
        setAxiosDefaults(token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        },
        showErrorAlert(message) {
            Swal.fire({
                icon: 'error',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
            });
        },
        showSuccessAlert(message) {
            Swal.fire({
                icon: 'success',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            })
        },
        showErrorAlert(message) {
            Swal.fire({
                icon: 'error',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            })
        },
        beforeDestroy() {
            if (this.tokenRefreshInterval) {
                clearInterval(this.tokenRefreshInterval);
            }
        }
    },
    mounted() {
        if (!this.authToken) {
            Swal.fire({
                icon: "error",
                title: "Authentication Error",
                text: "Auth token is missing. Please log in again.",
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
            }).then(() => {
                this.clearSession();
                this.logout();
            });
        } else {
            this.fetchOffices();
            this.userName = this.user.nama_lengkap || 'Nama User';
            this.userRole = this.user.user_level ? this.user.user_level.level_name : 'Role';
        }
        this.setupAxiosInterceptors();

        this.tokenRefreshInterval = setInterval(async () => {
            try {
                await this.handleTokenRefresh();
                console.log("Token refreshed successfully.");
            } catch (error) {
                console.error("Error refreshing token:", error);
                this.logout();
                this.$router.push({ name: "Login" }); // Pastikan "Login" adalah nama rute untuk halaman login
            }
        }, 1000 * 60 * 60 * 24); // Refresh token setiap 1 menit
    },
}
</script>

<template>
    <aside class="navbar navbar-vertical navbar-expand-lg bg-dark" data-bs-theme="dark">
        <div class="container-fluid">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu"
                aria-controls="sidebar-menu" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <h1 class="navbar-brand navbar-brand-autodark">
                <router-link to="/dashboard" class="text-left mt-3">
                    <div class="d-flex">
                        <img src="/assets/img/logo.png" style="height: 60px;" alt="Logo PLN" class="" />
                        <div class="justify-content-start align-items-center ms-2">
                            <h1 style="font-size: 18px; line-height: 20px; margin-top: 15px;">
                                CCTV STREAM
                            </h1>
                            <h1 style="font-size: 12px; line-height: 20px; margin-top: -15px;">
                                PLN UID KALBAR
                            </h1>
                        </div>
                    </div>
                </router-link>
            </h1>
            <div class="navbar-nav flex-row d-lg-none">
                <div class="nav-item mt-2 dropdown">
                    <a href="#" class="nav-link d-flex lh-1 text-reset p-0" data-bs-toggle="dropdown"
                        aria-label="Open user menu">
                        <i class="fa fa-user"></i>
                    </a>
                    <div class="dropdown-menu dropdown-menu-end dropdown-menu-arrow">
                        <div class="d-xl-block ps-2">
                            <div>{{ userName }}</div>
                            <div class="mt-1 small text-white">
                                {{ userRole }}
                            </div>
                        </div>
                        <div class="dropdown-divider"></div>
                        <router-link to="/manage/pengaturan" class="dropdown-item">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-cog"></i>
                            </span>
                            Pengaturan
                        </router-link>

                        <a href="#" class="dropdown-item" @click.prevent="confirmLogout">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-sign-out-alt"></i>
                            </span>
                            <span class="nav-link-title"> Logout </span>
                        </a>
                    </div>
                </div>
            </div>

            <div class="collapse navbar-collapse" id="sidebar-menu">
                <ul class="navbar-nav py-5 py-lg-2">
                    <li class="nav-item mt-2" :class="{ active: $route.path === '/dashboard' }">
                        <router-link class="nav-link" to="/dashboard">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-dashboard"></i>
                            </span>
                            <span class="nav-link-title"> Dashboard </span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2 dropdown" v-if="filteredOffices.length > 0">
                        <a class="nav-link dropdown-toggle" href="#navbar-cctv-multiple-stream"
                            data-bs-toggle="dropdown" data-bs-auto-close="false" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-video"></i>
                            </span>
                            <span class="nav-link-title"> CCTV Multiple Stream </span>
                        </a>
                        <div class="dropdown-menu">
                            <div class="dropdown-menu-columns">
                                <div class="dropdown-menu-column">
                                    <router-link v-for="office in filteredOffices" :key="office.id"
                                        :to="`/manage/cctv-multiple-stream/${office.id}`"
                                        class="dropdown-item py-2 nav-link-title-submenu">
                                        {{ office.office_short_name }}
                                    </router-link>
                                </div>
                            </div>
                        </div>
                    </li>

                    <li class="nav-item mt-2 dropdown" v-if="filteredOffices.length > 0">
                        <a class="nav-link dropdown-toggle" href="#navbar-cctv-single-stream" data-bs-toggle="dropdown"
                            data-bs-auto-close="false" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-video"></i>
                            </span>
                            <span class="nav-link-title"> CCTV Single Stream </span>
                        </a>
                        <div class="dropdown-menu">
                            <div class="dropdown-menu-columns">
                                <div class="dropdown-menu-column">
                                    <router-link v-for="office in filteredOffices" :key="`single-${office.id}`"
                                        :to="`/manage/cctv-single-stream/${office.id}`"
                                        class="dropdown-item py-2 nav-link-title-submenu">
                                        {{ office.office_short_name }}
                                    </router-link>
                                </div>
                            </div>
                        </div>
                    </li>

                    <li class="nav-item mt-2" v-if="[1, 2, 3].includes(user.user_level.id)" :class="{
                        active: $route.path === '/manage/live-monitoring-project'
                    }">
                        <router-link class="nav-link" to="/manage/live-monitoring-project">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-video"></i>
                            </span>
                            <span class="nav-link-title"> Live Monitoring Project</span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2" v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)" :class="{
                        active: $route.path === '/manage/person-detection-logs'
                    }">
                        <router-link class="nav-link" to="/manage/person-detection-logs">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-users"></i>
                            </span>
                            <span class="nav-link-title"> Person Detection Logs</span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2" v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)" :class="{
                        active: $route.path === '/manage/security-patrol-logs'
                    }">
                        <router-link class="nav-link" to="/manage/security-patrol-logs">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-user-secret"></i>
                            </span>
                            <span class="nav-link-title"> Security Patrol Logs</span>
                        </router-link>
                    </li>
                    <li class="nav-item mt-2" v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)" :class="{
                        active: $route.path === '/manage/plate-number-detection-logs'
                    }">
                        <router-link class="nav-link" to="/manage/plate-number-detection-logs">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-car"></i>
                            </span>
                            <span class="nav-link-title"> Plate Number Detection Logs</span>
                        </router-link>
                    </li>
                    <li class="nav-item mt-2" v-if="[1, 2, 3, 4, 5, 7].includes(user.user_level.id)" :class="{
                        active: $route.path === '/manage/realtime-detection'
                    }">
                        <router-link class="nav-link" to="/manage/realtime-detection">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-receipt"></i>
                            </span>
                            <span class="nav-link-title"> MQTT Detection Logs</span>
                        </router-link>
                    </li>
                    <li v-if="user.user_level.id == 1" class="nav-item mt-2" :class="{
                        active: $route.path === '/manage/subject-label-ai'
                    }">
                        <router-link class="nav-link" to="/manage/subject-label-ai">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-robot"></i>
                            </span>
                            <span class="nav-link-title"> Subject / Label AI</span>
                        </router-link>
                    </li>
                    <li v-if="user.user_level.id <= 10" class="nav-item mt-2" :class="{
                        active: $route.path === '/manage/face-collection'
                    }">
                        <router-link class="nav-link" to="/manage/face-collection">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-camera"></i>
                            </span>
                            <span class="nav-link-title"> Face Collection</span>
                        </router-link>
                    </li>
                    <li class="nav-item mt-2" v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)"
                        :class="{ active: $route.path === '/manage/list-unknown-people' }">
                        <router-link class="nav-link" to="/manage/list-unknown-people">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-users"></i>
                            </span>
                            <span class="nav-link-title"> List Unknown People </span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2 dropdown" v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)">
                        <a class="nav-link dropdown-toggle" href="#navbar-base" data-bs-toggle="dropdown"
                            data-bs-auto-close="false" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-folder"></i>
                            </span>
                            <span class="nav-link-title"> Manajemen Data </span>
                        </a>
                        <div class="dropdown-menu" :class="{
                            show: $route.path.startsWith('/manage/manajemen-data')
                        }">
                            <div class="dropdown-menu-columns">
                                <div class="dropdown-menu-column">
                                    <router-link v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/users')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/users">
                                        Users
                                    </router-link>
                                    <router-link v-if="[1, 2, 3, 4, 7].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/plate-number')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/plate-number">
                                        Plate Number
                                    </router-link>
                                    <router-link v-if="[1, 2, 3, 7].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/office')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/office">
                                        Office
                                    </router-link>
                                    <router-link v-if="[1, 2, 3, 7].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/building')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/building">
                                        Building
                                    </router-link>
                                    <router-link v-if="[1, 2, 3, 7].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/cctv')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/cctv">
                                        CCTV
                                    </router-link>
                                    <router-link v-if="[1, 2, 3].includes(user.user_level.id)" :class="{
                                        active: $route.path.startsWith('/manage/manajemen-data/cctv-live-monitoring-project')
                                    }" class="dropdown-item py-2 nav-link-title-submenu"
                                        to="/manage/manajemen-data/cctv-live-monitoring-project">
                                        CCTV Live Monitoring Project
                                    </router-link>
                                </div>
                            </div>
                        </div>
                    </li>

                    <li class="nav-item mt-2" :class="{
                        active: $route.path === '/manage/pengaturan'
                    }">
                        <router-link class="nav-link" to="/manage/pengaturan">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-cog"></i>
                            </span>
                            <span class="nav-link-title"> Pengaturan </span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2">
                        <router-link class="nav-link" to="/">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-arrow-left"></i>
                            </span>
                            <span class="nav-link-title"> Back to Portal</span>
                        </router-link>
                    </li>

                    <li class="nav-item mt-2">
                        <a href="#" class="nav-link" @click.prevent="confirmLogout">
                            <span class="nav-link-icon d-md-none d-lg-inline-block">
                                <i class="fa fa-sign-out-alt"></i>
                            </span>
                            <span class="nav-link-title"> Logout </span>
                        </a>
                    </li>

                </ul>
            </div>
        </div>
    </aside>
</template>
