<script setup>
  import { VForm } from 'vuetify/components/VForm'
  import { themeConfig } from '@themeConfig'
  import { decodeCredential } from 'vue3-google-login'

  const { setAlert } = useAlert()

  //Forçar Claro
  import { useConfigStore } from '@core/stores/config'
  const configStore = useConfigStore()
  configStore.theme = 'light'

  const isPasswordVisible = ref(false)
  const route = useRoute()
  const router = useRouter()
  const ability = useAbility()

  const errors = ref({
    email: undefined,
    password: undefined,
  })

  const refVForm = ref()

  const credentials = ref({
    email: '',
    password: '',
  })

  const rememberMe = ref(false)

  const login = async () => {
    try {
      const res = await $api('/conta/login', {
        method: 'POST',
        body: {
          info: credentials.value.email,
          password: credentials.value.password,
          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! Você será redirecionado...', 'success', 'tabler-check', 5000)

      await nextTick(() => {
        router.replace(route.query.to ? String(route.query.to) : '/')
      })
    } catch (err) {
      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)

    }

  }

  const onSubmit = () => {
    refVForm.value?.validate().then(({ valid: isValid }) => {
      if (isValid)
        login()
    })
  }

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

<template>

  <VRow no-gutters class="auth-wrapper bg-surface justify-center align-center bk-login-register">

    <VCol cols="12" lg="4" class="auth-card-v2 d-flex align-center justify-center flex-wrap"
      style="background-color: white; border-radius: 10px;">
      <VCard flat :max-width="500" class="pa-4">
        <VCardText class="text-center pt-0">

          <img src="@images/logo.png" alt="logo" style="width: 28%; max-width: 100%; height: auto;">

          <h4 class="text-h4 mb-2">
            Bem vindo ao <span class="text-capitalize"> {{ themeConfig.app.title }} </span>
          </h4>
          <p class="mb-0">
            Faça login para continuar
          </p>
        </VCardText>

        <VCardText class="pb-0">
          <VForm ref="refVForm" @submit.prevent="onSubmit">
            <VRow>
              <!-- 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="credentials.email" label="Email/Telefone"
                  placeholder="Insira o email ou telefone" autofocus :rules="[requiredValidator]" />
              </VCol>

              <!-- password -->
              <VCol cols="12">
                <AppTextField v-model="credentials.password" label="Senha" placeholder="············"
                  :rules="[requiredValidator]" :type="isPasswordVisible ? 'text' : 'password'"
                  :error-messages="errors.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 block type="submit">
                  Login
                </VBtn>
              </VCol>


              <VCol cols="12" class="text-center">
                <p class="mb-0">Ainda não possuí conta?</p>
                <RouterLink :to="{ name: 'register' }">
                  Clique aqui para se registrar
                </RouterLink>
              </VCol>

              <VCol cols="12" class="text-center mt-4">
                <RouterLink :to="{ name: 'index' }">
                  <VIcon icon="tabler-home" /> Voltar para o início
                </RouterLink>
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </VCol>
  </VRow>
</template>

<style lang="scss">
  @use "@core/scss/template/pages/page-auth.scss";
</style>
