<script setup>
import { useAppAbility } from '@/plugins/casl/useAppAbility';
import axios from '@axios';
import {
    emailValidator,
    requiredEmail,
    requiredPassword
} from '@validators';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const ability = useAppAbility()
const errors = ref({
    password: undefined,
    email: undefined,
})
const inavlid = ref(false);
const InvalidCredential = ref()
const isLoadingVisible = ref(false)
const isPasswordVisible = ref(false)
const isPolicy = ref(false)
const isDisabled = ref(true)
const isDialogVisible = ref(false)
const refVForm = ref()
const password = ref()
const email = ref()
const seetingPlanLogo = ref();
const onSubmit = () => {
    inavlid.value = false;
    InvalidCredential.value = '';
    refVForm.value?.validate().then(({ valid: isValid }) => {
        if (isValid)
            loginPatient()
    })
}
onMounted(async () => {
    const layoutWrapper = document.querySelector('.layout-wrapper');

    // Check if the element exists
    if (layoutWrapper) {
        // Add the class you want
        layoutWrapper.classList.add('regbg');
    }
    localStorage.setItem('thank-you-page', 'no')
    let setting = await axios.post('/api/settings', {})
    console.log(setting.data)
    seetingPlanLogo.value = '/assets/logo/' + setting.data.logo
})
onUnmounted(() => {
    // Select the element by class name
    const layoutWrapper = document.querySelector('.layout-wrapper');

    // Check if the element exists
    if (layoutWrapper) {
        // Remove the class
        layoutWrapper.classList.remove('regbg');
    }
});
const loginPatient = () => {
    isLoadingVisible.value = true;
    axios.post('/agent/login-agent', {
        email: email.value,
        password: password.value,
    }).then(r => {
        console.log(r.data);
        localStorage.setItem('access_token', r.data.access_token)
        localStorage.setItem('agent_id', r.data.data.id)
        localStorage.setItem('user_role', 'agent')
        localStorage.setItem('userAbilities', '[{"action":"manage","subject":"all"}]')
        const userAbilities = [{ "action": "manage", "subject": "all" }];
        ability.update(userAbilities)
        router.replace(route.query.to && route.query.to != '/provider/login' ? String(route.query.to) : '/provider/dashboard')
    }).catch(error => {

        console.error("Invalid Credentials", error);
        console.error("Invalid Credentials", error.response.data.message);
        if (error.response && error.response.data.message) {
            inavlid.value = true;
            console.error("Invalid Credentials");
            InvalidCredential.value = "Sorry, that email or password didn't work.";
        }

        isLoadingVisible.value = false;

    });

}
</script>

<template>
    <div class="auth-wrapper d-flex align-center justify-center pa-4">
        <VCard class="auth-card pa-2 pt-0 rounded-5 regbx" max-width="320">
            <VCardItem class="justify-center">
                <VCardTitle class="text-2xl font-weight-bold text-primary">
                    <VImg :src="seetingPlanLogo" width="250" height="50" class="logo-img" />
                </VCardTitle>
                <VDialog v-model="isLoadingVisible" width="110" height="150" color="primary">
                    <VCardText class="" style="color: white !important;">
                        <div class="demo-space-x">
                            <VProgressCircular :size="40" color="primary" indeterminate />
                        </div>
                    </VCardText>
                </VDialog>
            </VCardItem>
            <VCardText>
                <VForm ref="refVForm" @submit.prevent="onSubmit">
                    <VRow>
                        <VCol cols="12"></VCol>
                        <VRow class="bg-white">
                            <VCol cols="12">
                                <VTextField v-model="email" label="Email" type="email"
                                    :rules="[requiredEmail, emailValidator]" :error-messages="errors.email" />
                            </VCol>
                            <!-- email -->
                            <VCol cols="12">
                                <VTextField v-model="password" label="Password" placeholder="············"
                                    :rules="[requiredPassword]" :type="isPasswordVisible ? 'text' : 'password'"
                                    :append-inner-icon="isPasswordVisible ? 'bx-show' : 'bx-hide'"
                                    @click:append-inner="isPasswordVisible = !isPasswordVisible" />
                            </VCol>
                            <!-- password -->
                            <VCol cols="12">
                                <p class="error-message" v-if="inavlid">{{ InvalidCredential }}</p>
                                <!-- login button -->
                                <VBtn block type="submit"
                                    style="background-color: rgb(var(--v-theme-yellow-theme-button)) !important;">
                                    Login
                                </VBtn>
                            </VCol>
                            <!-- <VCol cols="12">
                <VBtn block to="/provider/register" >
                  Register
                </VBtn>
              </VCol> -->
                            <!-- <VCol cols="12" class="text-center text-base px-0 py-0 mb-3"   style="background-color: rgb(var(--v-theme-yellow-theme-button)) !important;">
              <span>Don't have an account?</span>
              <RouterLink class="text-primary" to="/register">
                Register
              </RouterLink>
            </VCol> -->
                        </VRow>
                        <VCol cols="12" class="text-center text-base px-0 py-0 mb-0 mt-7 text-yellow-theme-button">
                            <span> Don't have an account? </span>
                            <RouterLink class="text-yellow-theme-button" to="/provider/register"
                                style="text-decoration: underline;">
                                Register
                            </RouterLink>
                        </VCol>
                    </VRow>
                </VForm>

            </VCardText>
        </VCard>

    </div>
</template>

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

.regbg {
    background-image: url('/assets/images/reg_bg.png');
    background-size: cover;
    background-repeat: no-repeat;
}

.regbx {
    background-color: rgb(var(--v-theme-yellow));
    box-shadow: 0px 0px 10px #ccc;
    border-radius: 10px;
}

.error-message {
    color: #ff2f2f;
    font-size: 15px;
}

.bg-primary {
    background-color: rgb(var(--v-theme-grey-800)) !important;
}
</style>
