<script setup>
    import NavBarNotifications from './NavBarNotifications.vue'
    import { decodeCredential } from 'vue3-google-login'
    import { PerfectScrollbar } from 'vue3-perfect-scrollbar'
    const props = defineProps({
        isDrawerOpen: {
            type: Boolean,
            required: true,
        },
        userData: Object
    })

    const emit = defineEmits([
        'update:isDrawerOpen',
        'updateAvatar'
    ])


    import { useAlert } from '@/composables/useAlert'
    const { setAlert } = useAlert()

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

    const userData = useCookie('userData')
    const userAbilityRules = useCookie('userAbilityRules')
    const accessToken = useCookie('accessToken')

    const logado = ref(userData?.value?.id !== undefined && userData?.value?.id !== null)

    const { width: windowWidth } = useWindowSize()
    const isMobile = ref(false)

    isMobile.value = windowWidth.value < 768

    watch(windowWidth, () => {
        isMobile.value = windowWidth.value < 768
    })

    const handleDrawerModelValueUpdate = val => {
        emit('update:isDrawerOpen', val)
    }

    const closeDrawer = () => {
        emit('update:isDrawerOpen', false)
    }

    const actionsIcon = [
        {
            title: 'Candidaturas',
            icon: 'tabler-briefcase',
            to: '/minhas-candidaturas'
        },
        {
            title: 'Ingressos',
            icon: 'tabler-ticket',
            to: '/meus-ingressos'
        },
        {
            title: 'Notificações',
            icon: 'tabler-bell',
        }
    ]

    const configList = ref([
        {
            title: 'Editar Perfil',
            icon: 'tabler-user-edit',
            to: '/editar-perfil',
            show: true
        },
        {
            title: 'Meu currículo',
            icon: 'tabler-file-text',
            to: '/meu-curriculo',
            show: true
        },
        {
            title: 'Painel do Recrutador',
            icon: 'tabler-briefcase',
            to: '/redirect/gestor',
            show: userData?.value?.role === 'recrutador' ? true : false,
            destaque: true
        },
        {
            title: 'Painel do Promotor',
            icon: 'tabler-ticket',
            to: '/redirect/gestor',
            show: userData?.value?.role === 'promotor' ? true : false,
            destaque: true
        },
        {
            title: 'Torne-se um Gestor',
            icon: 'tabler-briefcase',
            to: 'https://gestor.akkiperto.com.br/seja-um-gestor',
            show: userData?.value?.role === 'cliente' ? true : false,
            destaque: true
        },
        {
            title: 'Sair da Conta',
            icon: 'tabler-logout',
            to: 'logout',
            show: true
        }
    ])

    const irPara = (to) => {
        if (to === 'logout') return logout()

        if (to.includes('http')) {
            window.open(to, '_blank')
            closeDrawer()
            return
        }

        router.push(to)
        closeDrawer()
    }

    const logout = async () => {

        // Remove "accessToken" from cookie
        useCookie('accessToken').value = null

        // Remove "userData" from cookie
        userData.value = null

        // ℹ️ We had to remove abilities in then block because if we don't nav menu items mutation is visible while redirecting user to login page

        // Remove "userAbilities" from cookie
        useCookie('userAbilityRules').value = null

        // Reset ability to initial ability
        ability.update([])

        //Aguardar 2 segundos para redirecionar
        await new Promise(resolve => setTimeout(resolve, 2000))

        //Redirect to login page
        window.location.href = '/'
    }

    const esqueceuSenha = () => {
        router.push({ name: 'esqueci-senha' })
    }

    const viewRegister = ref(false)

    /*
    * Login 
    */
    const rememberMe = ref(false)
    const isPasswordVisible = ref(false)
    const emailLogin = ref('')
    const passwordLogin = ref('')
    const loadingLogin = ref(false)

    const login = async () => {
        loadingLogin.value = true
        try {
            const res = await $api('/conta/login', {
                method: 'POST',
                body: {
                    info: emailLogin.value,
                    password: passwordLogin.value,
                    rememberMe: rememberMe.value,
                },
            })

            if (!res) return

            const { accessToken, userData, userAbilityRules } = res.response

            const userAbilityRulesCookie = useCookie('userAbilityRules').value; // Lê a string do cookie
            const userAbilityRulesJSON = JSON.parse(userAbilityRules); // Converte a string para um objeto/array JavaScript

            ability.update(userAbilityRulesJSON);

            console.log('abilitylogin', ability)


            const cookieOptions = {};

            if (rememberMe.value) {
                cookieOptions.maxAge = 25 * 24 * 60 * 60;
            }

            useCookie('userData', cookieOptions).value = userData;
            useCookie('userAbilityRules', cookieOptions).value = userAbilityRules;
            useCookie('accessToken', cookieOptions).value = accessToken;

            setAlert('Login realizado com sucesso!', 'success', 'tabler-check', 5000)
            loadingLogin.value = false

            setTimeout(() => {
                router.go()
            }, 2000)
        } catch (err) {
            loadingLogin.value = false
            console.error('Login Erro', err.response)
            setAlert(err.response?._data?.message || 'Erro ao fazer login. Tente novamente mais tarde.', 'error', 'tabler-alert-triangle', 7000)

        }
    }

    const callback = async response => {
        // This callback will be triggered when the user selects or login to
        // his Google account from the popup
        console.log("Handle the response", response)

        const dataUser = decodeCredential(response.credential)

        console.log('dataUser Google', dataUser)

        let email = dataUser.email

        if (!email || email === '') {
            setAlert('Erro ao fazer login com o Google. Tente novamente mais tarde.', 'error', 'tabler-alert-triangle', 5000)

            return
        }

        loadingLogin.value = true

        try {
            const res = await $api('/conta/login-g-auto', {
                method: 'POST',
                body: {
                    name: dataUser.name,
                    email,
                    rememberMe: true,
                    picture: dataUser.picture ? dataUser.picture : null,
                },
            })

            if (!res) return

            const { accessToken, userData, userAbilityRules } = res.response

            const userAbilityRulesCookie = useCookie('userAbilityRules').value; // Lê a string do cookie
            const userAbilityRulesJSON = JSON.parse(userAbilityRules); // Converte a string para um objeto/array JavaScript

            ability.update(userAbilityRulesJSON);

            console.log('abilitylogin', ability)


            const cookieOptions = {};

            if (rememberMe.value) {
                cookieOptions.maxAge = 25 * 24 * 60 * 60;
            }

            useCookie('userData', cookieOptions).value = userData;
            useCookie('userAbilityRules', cookieOptions).value = userAbilityRules;
            useCookie('accessToken', cookieOptions).value = accessToken;

            setAlert('Login realizado com sucesso!', 'success', 'tabler-check', 5000)
            loadingLogin.value = false

            router.go()

            /*Redirecionar para a rota que o usuário estava
            await nextTick(() => {
              window.location.reload()
            })*/

        } catch (err) {
            loadingLogin.value = false
            console.error('Login Erro', err, err.response)

            setAlert(err.response?._data?.message || 'Erro ao fazer login. Tente novamente mais tarde.', 'error', 'tabler-alert-triangle', 7000)

        }

    }

    /*
    * Registro
    */

    const loadingRegister = ref(false)
    const form = ref({
        fullName: '',
        email: '',
        telefone: '',
        password: '',
        confirmPassword: '',
        privacyPolicies: false,
    })

    const confirmPasswordValidator = (value) => {
        if (value !== form.value.password) {
            return 'As senhas não coincidem'
        }
        return true
    }


    const register = async () => {

        if (!form.value.privacyPolicies) {
            setAlert('Você precisa aceitar os termos de uso e condições e a política de privacidade.', 'error', 'tabler-alert-triangle', 5000)
            return
        }

        if (!form.value.fullName || !form.value.email || !form.value.telefone ||
            !form.value.password || !form.value.confirmPassword) {
            setAlert('Preencha todos os campos obrigatórios.', 'error', 'tabler-alert-triangle', 5000)
            return
        }

        if (form.value.password !== form.value.confirmPassword) {
            setAlert('As senhas não coincidem.', 'error', 'tabler-alert-triangle', 5000)
            return
        }

        if (!form.value.email.includes('@') || !form.value.email.includes('.')) {
            setAlert('Email inválido.', 'error', 'tabler-alert-triangle', 5000)
            return
        }

        try {
            const res = await $api('/conta/register', {
                method: 'POST',
                body: {
                    fullName: form.value.fullName,
                    email: form.value.email,
                    telefone: form.value.telefone,
                    password: form.value.password,
                },
            })

            console.log('Register Response: ', res)

            const { accessToken, userData, userAbilityRules } = res.response

            const userAbilityRulesJSON = JSON.parse(userAbilityRules)

            console.log('userAbilityRules', userAbilityRules)

            ability.update(userAbilityRulesJSON)

            console.log(ability)

            useCookie('accessToken').value = accessToken
            useCookie('userData').value = userData

            const cookieOptions = {
                maxAge: 25 * 24 * 60 * 60
            }

            useCookie('userData', cookieOptions).value = userData;
            useCookie('userAbilityRules', cookieOptions).value = userAbilityRulesJSON
            useCookie('accessToken', cookieOptions).value = accessToken;

            setAlert('Cadastro realizado com sucesso! Você será redirecionado...', 'success', 'tabler-check', 5000)
            setTimeout(() => {
                router.go()
            }, 2000)
        } catch (error) {
            console.error('Register Error: ', error, error.response)
            setAlert(error.response?._data?.message || 'Erro ao fazer cadastro. Tente novamente mais tarde.', 'error', 'tabler-alert-triangle', 5000)
        }
    }

    const clickAvatar = () => {
        document.getElementById('fileInput').click()
    }

    const uploadAvatar = async (e) => {

        if (!logado) return

        const file = e.target.files[0]

        if (!file) return

        const formData = new FormData()
        formData.append('avatar', file)

        try {
            const res = await $api(`/users/updateAvatar/${userData?.value?.id}`, {
                method: 'PUT',
                body: formData
            })

            if (!res) return

            const avatar = res

            console.log('avatar', avatar)

            useCookie('userData').value = { ...userData.value, avatar }

            setAlert('Foto de perfil atualizada com sucesso!', 'success', 'tabler-check', 5000)

            emit('updateAvatar', avatar)

        } catch (err) {
            console.error('Erro ao atualizar avatar', err, err.response)
            setAlert('Erro ao atualizar foto. Tente novamente mais tarde.', 'error', 'tabler-alert-triangle', 3000)
        }
    }


</script>

<template>
    <VDialog :max-width="!isMobile ? 500 : ''" :fullscreen="isMobile ? true : false" temporary
        z-index="9999999999999000" transition="dialog-top-transition" class="scrollable-content"
        :model-value="props.isDrawerOpen" @update:model-value="handleDrawerModelValueUpdate" height="100%">

        <template v-if="logado">
            <VCard elevation="0" color="primary" variant="flat" class="align-center justify-center"
                style="min-height: 50%;">
                <VIcon icon="tabler-arrow-left" size="30" class="position-absolute"
                    style="top: 10px; left: 10px; cursor: pointer; margin-bottom: 50px; padding-top: 15px;"
                    @click="closeDrawer" color="white" />
                <VBadge color="white" bordered location="top right" icon="tabler-pencil" style="cursor: pointer;"
                    class="badge-editar-perfil" @click="clickAvatar()">
                    <input type="file" style="display: none;" @change="uploadAvatar" ref="fileInput" id="fileInput" />
                    <VAvatar size="90" :color="!(props.userData && props.userData?.avatar) ? 'white' : undefined"
                        :variant="!(props.userData && props.userData?.avatar) ? 'tonal' : undefined"
                        class="avatar-img-perfil">
                        <VImg v-if="props.userData && props.userData?.avatar" :src="props.userData?.avatar" cover />
                        <VIcon v-else icon="tabler-user" size="55" />
                    </VAvatar>
                </VBadge>
                <h3 style="color: white;" class="mt-2">{{ props.userData?.fullName }}</h3>
                <p>{{ props.userData?.email }}</p>
                <div class="linha-icons mt-2" :style="`grid-template-columns: repeat(${actionsIcon.length}, 75px);`">
                    <div class="d-flex align-center flex-column text-center" v-for="action in actionsIcon"
                        :key="action.title" @click="closeDrawer">
                        <VBtn v-if="action.title === 'Notificações'" icon color="white" style="background: white;">
                            <NavBarNotifications />
                        </VBtn>
                        <VBtn v-else :to="action.to" icon color="white" style="background: white;">
                            <VIcon :icon="action.icon" size="23" />
                        </VBtn>
                        <p class="text-center mt-2" style="font-size: 12px;">{{ action.title }}</p>
                    </div>
                </div>
            </VCard>
            <VCard elevation="0" color="white" variant="flat" class="px-2"
                style="min-height: calc(50% + 50px);border-radius: 15px 15px 0px 0px !important;"
                :style="isMobile ? 'margin-top: -50px !important;' : 'margin-top: -30px !important;'">
                <h2 class="ml-2 mt-6">Configurações</h2>
                <VList class="w-100 mt-2">
                    <template v-for="config in configList" :key="config.title">
                        <VListItem @click="irPara(config.to)" v-if="config.show"
                            style="border-bottom: 1px #eaeaea solid;" class="py-4">
                            <div class="d-flex flex-row align-center justify-space-between">
                                <p class="font-weight-bold mb-0" style="font-size: 16px;"
                                    :style="config.destaque ? 'color: var(--color-akkiperto);' : ''">
                                    <VIcon :icon="config.icon" size="23" class="mr-3" /> {{ config.title }}
                                </p>
                                <VIcon icon="tabler-chevron-right" color="primary" size="23" />
                            </div>
                        </VListItem>
                    </template>
                </VList>
            </VCard>
        </template>

        <template v-else>
            <VCard elevation="0" color="white" variant="flat" class="px-6"
                style="min-height: 50%;border-bottom: 10px var(--color-akkiperto) solid; border-radius: 15px;"
                :style="viewRegister ? 'overflow: auto;' : 'overflow: hidden;'">


                <VIcon icon="tabler-arrow-left" size="30" class="position-absolute"
                    style="top: 10px; left: 10px; cursor: pointer; margin-bottom: 50px; padding-top: 15px;"
                    @click="closeDrawer" color="primary" />

                <v-slide-x-transition>
                    <VRow class="gap-0 align-center align-content-center" v-if="!viewRegister">
                        <VCardText class="text-center pt-15 pb-2">
                            <h4 class="text-h4 mb-2">
                                Bem vindo ao <span class="text-capitalize"> AkkiPerto </span>
                            </h4>
                            <p class="mb-0">
                                Faça login para continuar
                            </p>
                        </VCardText>
                        <!-- email -->
                        <VCol cols="12">
                            <p class="text-center mb-0">
                                <GoogleLogin :callback="callback" />
                            </p>
                            <p class="my-3 text-center">
                                ou
                            </p>
                            <AppTextField v-model="emailLogin" label="Email/Telefone"
                                placeholder="Insira o email ou telefone" autofocus :rules="[requiredValidator]" />
                        </VCol>
                        <!-- password -->
                        <VCol cols="12">
                            <AppTextField v-model="passwordLogin" label="Senha" placeholder="············"
                                :rules="[requiredValidator]" :type="isPasswordVisible ? 'text' : 'password'"
                                :append-inner-icon="isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                                @click:append-inner="isPasswordVisible = !isPasswordVisible" />
                            <div class="d-flex align-center flex-wrap justify-space-between mt-1 mb-4">
                                <VCheckbox v-model="rememberMe" label="Lembrar-me" />
                                <a class="text-primary ms-2 mb-1" style="cursor: pointer;" @click="esqueceuSenha">
                                    Esqueceu sua senha?
                                </a>
                            </div>
                            <VBtn @click="login" color="primary" class="w-100" :loading="loadingLogin">
                                <p class="mb-0">Entrar</p>
                            </VBtn>
                        </VCol>
                        <VCol cols="12" class="text-center mb-5">
                            <p class="mb-0">Ainda não possuí conta?</p>
                            <p class="text-primary cursor-pointer" @click="viewRegister = true">
                                Clique aqui para se registrar
                            </p>
                        </VCol>
                    </VRow>
                </v-slide-x-transition>

                <v-slide-x-transition>
                    <VRow class="gap-0 align-center align-content-center" v-if="viewRegister">
                        <VCardText class="text-center pt-15 pb-2">
                            <h4 class="text-h4 mb-2">
                                Bem vindo ao <span class="text-capitalize"> AkkiPerto </span>
                            </h4>
                            <p class="mb-0">
                                Crie sua conta para continuar
                            </p>
                        </VCardText>
                        <!-- email -->
                        <VCol cols="12">
                            <p class="text-center mb-0">
                                <GoogleLogin :callback="callback" />
                            </p>
                            <p class="my-3 text-center">
                                ou
                            </p>
                            <AppTextField v-model="form.email" label="Email" placeholder="seuemail@email.com"
                                type="email" autofocus :rules="[requiredValidator, emailValidator]" />
                        </VCol>

                        <!-- Nome -->
                        <VCol cols="12">
                            <AppTextField v-model="form.fullName" :rules="[requiredValidator]" label="Nome"
                                placeholder="Insira o seu nome" required />
                        </VCol>

                        <!-- telefone -->
                        <VCol cols="12">
                            <AppTextField v-model="form.telefone" :rules="[requiredValidator]" label="Telefone"
                                placeholder="(00) 00000-0000" v-mask="'(##) #####-####'" />
                        </VCol>

                        <VCol cols="12">
                            <p class="mb-0 font-weight-bold">
                                <VIcon icon="tabler-lock" class="mr-1" />
                                Crie sua senha
                            </p>
                        </VCol>


                        <!-- password -->
                        <VCol cols="12">
                            <AppTextField v-model="form.password" :rules="[requiredValidator]" label="Senha"
                                placeholder="············" :type="isPasswordVisible ? 'text' : 'password'"
                                :append-inner-icon="isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                                @click:append-inner="isPasswordVisible = !isPasswordVisible" />
                        </VCol>

                        <VCol cols="12">
                            <AppTextField v-model="form.confirmPassword"
                                :rules="[requiredValidator, confirmPasswordValidator]" label="Confirme sua Senha"
                                placeholder="············" :type="isPasswordVisible ? 'text' : 'password'"
                                :append-inner-icon="isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                                @click:append-inner="isPasswordVisible = !isPasswordVisible" />

                        </VCol>

                        <VCol cols="12">
                            <div class="d-flex align-center mt-2 mb-4">
                                <VCheckbox id="privacy-policy" v-model="form.privacyPolicies" inline
                                    aria-checked="true" />
                                <VLabel for="privacy-policy" style="opacity: 1;">
                                    <span class="me-1">Eu aceito os</span>
                                    <a href="/termos-de-uso" class="text-primary mr-1">termos de uso</a>
                                    <span class="me-1">e a</span>
                                    <a href="/politica-de-privacidade" class="text-primary">política de
                                        privacidade.</a>
                                </VLabel>
                            </div>

                            <VBtn block @click="register" color="primary" :loading="loadingRegister">
                                Cadastrar
                            </VBtn>
                        </VCol>

                        <!-- create account -->
                        <VCol cols="12" class="text-center text-base">
                            <span>Já tem uma conta?</span>
                            <p class="text-primary cursor-pointer" @click="viewRegister = false">
                                Faça login
                            </p>
                        </VCol>
                    </VRow>
                </v-slide-x-transition>


            </VCard>
        </template>

    </VDialog>
</template>