<script setup>
import axios from '@axios';
import avatar1 from '@images/avatars/avatar-1.png';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const router = useRouter()
const route = useRoute()
const profileName = ref();
const profileImg = ref(null)
const role_id = ref();
const categories = ref([]);
const answerCategory = ref(0);
const categoryLength = ref();
const percentage = ref();
const currentUser = ref(localStorage.getItem('user_role'));
const access_token = localStorage.getItem('access_token');
const isConferncePageForPatient = computed(() => store.getters.getCurrentPage === '/queue');
const showHomeBtn = ref(false)
const isMobile = ref(window.innerWidth <= 768);
const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768;
};
onMounted(async () => {
    console.log('store.getters.getPatient.url', store.getters.getPatient.url)
    window.addEventListener('resize', checkMobile);
    if (currentUser.value == 'patient') {
        await store.dispatch('getPatientInfo')
        await store.dispatch('getCategory')
        categories.value = store.getters.getCategories.data;
        categoryLength.value = categories.value.length;
        console.log("categoriesLength", categories.value.length);
    }

    if (route.path === '/provider/patient-profile') {
        showHomeBtn.value = true
    }
    router.beforeEach((to, from, next) => {
        if (to.fullPath === '/provider/patient-profile') {
            showHomeBtn.value = true
        }
        // console.log('Navigating from', from.fullPath, 'to', to.fullPath);
        next(); // Don't forget to call next() to continue navigation
    });
    // console.log("currentUser", currentUser.value);
    const access_token = localStorage.getItem('access_token');
    if (currentUser.value == 'patient') {
        // console.log("patient", currentUser.value);
        role_id.value = localStorage.getItem('patient_id')
        await axios.post('/api/get-patient-detail/' + role_id.value, {
            headers: {
                'Authorization': `Bearer ${access_token}`,
            }
        })
            .then(response => {
                // console.log('Response:', response.data);
                if (response.data) {
                    let patientData = response.data.patient
                    profileName.value = patientData.first_name + ' ' + patientData.last_name
                    profileImg.value = patientData.profile_picture
                    // console.log("profileName", profileName.value);
                } else {
                    isLoadingVisible.value = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });

    }
    if (currentUser.value == 'agent') {
        // console.log("Agent", currentUser.value);
        await axios.post('/agent/api/agent-profile', {
            headers: {
                'Authorization': `Bearer ${access_token}`,
            }
        })
            .then(response => {
                // console.log('ResponseTest:', response.data);
                if (response.data) {
                    let patientData = response.data.ai_switch;
                    profileName.value = patientData.name;
                    // console.log("profileName", profileName.value);
                } else {
                    isLoadingVisible.value = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });

    }




});

const profilePercentage = computed(async () => {
    if (currentUser.value == 'patient') {
        await store.dispatch('getCategory')
        categories.value = store.getters.getCategories.data;
        categoryLength.value = categories.value.length;
        console.log("categoriesLength", categories.value.length);
        for (const cate of categories.value) {
            if (cate.question_count > 0) {
                answerCategory.value = answerCategory.value + 1;
            }
        }
        percentage.value = Math.round((answerCategory.value / categoryLength.value) * 100);

    }
    console.log('--->percentage ', answerCategory.value, categories.value.length)
    percentage.value = Math.round((answerCategory.value / categoryLength.value) * 100);
})
const logout = () => {
    // const currentUser = localStorage.getItem('user_role');
    localStorage.removeItem('isLogin');
    localStorage.removeItem('patient_id');
    localStorage.removeItem('user_role');
    localStorage.removeItem('access_token');
    localStorage.removeItem('userAbilities');
    localStorage.removeItem('agent_id');
    localStorage.removeItem('appiontment-id');
    localStorage.removeItem('patient_appointment_id');
    localStorage.removeItem('cominguser');
    localStorage.removeItem('currentPage');
    localStorage.removeItem('profileCompleted');
    localStorage.removeItem('category_name');
    localStorage.removeItem('selectedSidebarMenu');
    localStorage.removeItem('plan_name');
    localStorage.removeItem('plan_price');
    localStorage.removeItem('email');
    localStorage.removeItem('selected_time_slot');
    localStorage.removeItem('patient_appointment_details');
    localStorage.removeItem('cart_products');
    localStorage.removeItem('cart_id');
    localStorage.removeItem('exist');
    if (currentUser.value == 'agent') {
        router.push('/provider/login');
    } else {
        router.push('/login');
    }

}
const skill = ref(20)
</script>

<template>
    <RouterLink v-if="currentUser == 'agent' && showHomeBtn" class="text-black" to="/provider/dashboard"
        style="float: left;position: absolute;" :style="isMobile ? 'left:20%' : ''">
        <VIcon class="me-2" icon="mdi-home" size="22" color="grey" />
    </RouterLink>
    <VBadge dot location="bottom right" offset-x="3" offset-y="3" color="success" bordered>
        <VAvatar class="cursor-pointer" color="grey-800" variant="tonal">
            <VImg :src="store.getters.getPatient.url ? store.getters.getPatient.url : avatar1" />

            <!-- SECTION Menu -->
            <VMenu activator="parent" width="230" location="bottom end" offset="14px">
                <VList>
                    <VListItem>
                        <template #prepend>
                            <VListItemAction start>
                                <VBadge dot location="bottom right" offset-x="3" offset-y="3" color="success">
                                    <VAvatar color="grey-800" variant="tonal">
                                        <VImg :src="profileImg ? profileImg : avatar1" />
                                    </VAvatar>
                                </VBadge>
                            </VListItemAction>
                        </template>

                        <VListItemTitle class="font-weight-semibold"
                            style="color: rgb(var(--v-theme-yellow-theme-button));">
                            {{ profileName }}
                        </VListItemTitle>
                        <VListItemSubtitle v-if="currentUser == 'agent'">Agent</VListItemSubtitle>
                        <VListItemSubtitle v-else>Patient</VListItemSubtitle>
                    </VListItem>
                    <VDivider v-if="currentUser == 'patient'" class="my-2" />

                    <!-- 👉 Profile -->
                    <!-- <VListItem link v-if="currentUser == 'patient'">
                        <template #prepend>
                            <VIcon class="me-2" icon="bx-user" size="22" />
                        </template>

                        <VListItemTitle>
                            <RouterLink class="text-black" to="/category">
                                Profile
                            </RouterLink>
                        </VListItemTitle>
                    </VListItem> -->

                    <!-- 👉 Settings -->
                    <VListItem link v-if="currentUser == 'patient'">
                        <template #prepend>
                            <VIcon class="me-2" icon="bx-cog" size="22" />
                        </template>

                        <VListItemTitle>
                            <RouterLink class="text-black" to="/account-settings">
                                Settings
                            </RouterLink>
                        </VListItemTitle>
                    </VListItem>

                    <!-- 👉 Pricing -->


                    <!-- 👉 FAQ -->


                    <!-- Divider -->
                    <VDivider class="my-2" />

                    <!-- 👉 Logout -->
                    <VListItem @click="logout">
                        <template #prepend>
                            <VIcon class="me-2" icon="bx-log-out" size="22" />
                        </template>

                        <VListItemTitle class="text-black">Logout</VListItemTitle>
                    </VListItem>
                </VList>
            </VMenu>
            <!-- !SECTION -->
        </VAvatar>

    </VBadge>
    <div v-if="profilePercentage"></div>
    <p class="ml-3 mt-3" style="color: #000;" v-if="!isConferncePageForPatient">{{
        profileName }}

        <!-- <router-link to="/category" v-if="currentUser == 'patient'">
            <div class="progress-label text-center"
                style="color: rgb(var(--v-theme-yellow-theme-button)); font-size: 10px;"
                v-if="!isConferncePageForPatient">Complete your profile {{ percentage }}%</div>
            <VProgressLinear :model-value="percentage" width="600" height="2" style="width:125px"
                class="gradient-progress" :rounded="true" v-if="!isConferncePageForPatient" />

        </router-link> -->
    </p>



</template>
<style lang="scss">
.gradient-progress .v-progress-linear__determinate {

    background: linear-gradient(to right, #f11d1d, #06f78a);
    /* Adjust colors as needed */
}
</style>
