<script setup>
import { useAppAbility } from '@/plugins/casl/useAppAbility';
import axios from '@axios';
import {
    emailValidator,
    requiredEmail,
    requiredPassword
} from '@validators';
import { onMounted } from 'vue';
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 isContent = ref()
const seetingPlanLogo = ref();
onMounted(async () => {
    const layoutWrapper = document.querySelector('.layout-wrapper');

    // Check if the element exists
    if (layoutWrapper) {
        // Add the class you want
        layoutWrapper.classList.add('regbg');
    }
    const baseUrl = window.location.hostname;
    // alert(baseUrl);
    if (baseUrl === 'localhost') {
        isContent.value = 'd-block';
    } else {
        isContent.value = 'd-none';
    }
    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 onSubmit = () => {
    inavlid.value = false;
    InvalidCredential.value = '';
    refVForm.value?.validate().then(({ valid: isValid }) => {
        if (isValid)
            loginPatient()
    })
}

const loginPatient = () => {
    isLoadingVisible.value = true;
    axios.post('/api/login-patient', {
        email: email.value,
        password: password.value,
    }).then(r => {
        console.log("Response", r.data);
        let patientData = r.data.data;

        localStorage.setItem('access_token', r.data.access_token)
        localStorage.setItem('patient_id', patientData.id)
        localStorage.setItem('user_role', 'patient')
        localStorage.setItem('cominguser', 'login')
        if (!patientData.dob || !patientData.gender || !patientData.marital_status || !patientData.height || !patientData.weight) {
            // localStorage.setItem('profileCompleted', '0')
        }

        localStorage.setItem('isLogin', 'true')
        localStorage.setItem('userAbilities', '[{"action":"manage","subject":"all"}]')
        const userAbilities = [{ "action": "manage", "subject": "all" }];
        ability.update(userAbilities)
        router.replace(route.query.to && route.query.to != '/login' ? String(route.query.to) : '/overview')
    }).catch(error => {
        inavlid.value = true;
        InvalidCredential.value = "Sorry, that email or password didn't work.";
        isLoadingVisible.value = false;
    });

};
const getStartedFun = () => {
    // isLoadingVisible.value = true
    // router.replace(route.query.to && route.query.to != '/' ? String(route.query.to) : '/plans')
};
</script>

<template>

    <div class="auth-wrapper d-flex align-center justify-center">
        <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>
                <div class="text-center  cursor-pointer "
                    style="width: 100%;position: relative;display: block; padding-top: 0%;">
                    <span class="text-center mr-2">
                        <VImg :src='seetingPlanLogo' width="250" height="50" class="logo-img" />
                    </span>
                    <p class="mb-0 mt-0">
                        Log in to your Account
                    </p>
                </div>
            </VCardText>

            <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> -->
            <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 Address" type="email"
                                    :rules="[requiredEmail, emailValidator]" :error-messages="errors.email"
                                    density="compact" />
                            </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" density="compact" />
                            </VCol>
                            <!-- password -->
                            <VCol cols="12" class="pt-0 pb-0">
                                <router-link to="/forgot" class="text-primary underline">Forgot Password?</router-link>
                                <!-- <RouterLink class="text-primary ms-2 mb-1">
                Forgot Password?
              </RouterLink> -->
                            </VCol>
                            <VCol cols="12">
                                <p class="error-message" v-if="inavlid">{{ InvalidCredential }}</p>
                                <!-- login button -->
                                <VBtn block type="submit">
                                    Login
                                </VBtn>
                            </VCol>
                            <VCol cols="12" :class="isContent" class="pt-0">
                                <!-- login button -->
                                <!-- <VBtn block @click="getStartedFun()">
                                    Get Started
                                </VBtn> -->
                            </VCol>
                            <!-- <VCol cols="12" class="text-center text-base px-0 py-0 mb-3">
              <span>Don't have an account?</span>
              <RouterLink class="text-primary" to="/register">
                Register
              </RouterLink>
            </VCol> -->
                        </VRow>
                    </VRow>
                </VForm>

            </VCardText>
        </VCard>

    </div>
    <!-- <Footer></Footer> -->
</template>

<style lang="scss">
@use "@core/scss/template/pages/page-auth.scss";
@import "@vendor/fonts/fontawesome.css";
@import "@vendor/fonts/tabler-icons.css";
@import "@vendor/css/rtl/core.css";
@import "@vendor/css/rtl/theme-default.css";
@import "@styles/css/demo.css";
@import "@vendor/libs/node-waves/node-waves.css";
@import "@vendor/css/pages/front-page-help-center.css";
@import "@vendor/css/pages/help-center-front-page.css";

.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;
}

.logo-img {
    display: block;
    position: relative;
    margin: 0 auto;
}

.v-card.v-card--flat.v-theme--light.v-card--density-default.v-card--variant-elevated.text-center.search-header.rounded-0 {
    block-size: 357px;
    inset-block-start: -185px;
}

body {
    display: block !important;
}

.bg-primary {
    background-color: rgb(var(--v-theme-yellow-theme-button)) !important;
}

a.nav-link.fw-medium {
    color: rgba(var(--v-theme-on-background), var(--v-high-emphasis-opacity));
}

.light-style .layout-navbar .menu-text {
    color: #5d596c !important;
}

span.app-brand-text.demo.menu-text.fw-bold.ms-2.ps-1 {
    color: #5d596c !important;
}

.navbar.landing-navbar {
    border-color: rgba(255, 255, 255, 68%) !important;
    background: white;
    margin: 0;
    border-radius: 0;
    box-shadow: 0px 10px 10px #00000029;
}

.landing-footer .footer-top {
    background-color: #1C5580;
    border-radius: none !important;
    /* background: url("/assets/img/front-pages/backgrounds/footer-bg-dark.png"); */
}

.footer-bottom.py-3 {
    background-color: #282c3e;
}

.light-style .landing-footer .footer-link,
.light-style .landing-footer .footer-text {
    color: #d3d4dc !important;
}

.light-style .landing-footer .footer-link,
.light-style .landing-footer .footer-text {
    color: #d3d4dc;
}

a.footer-link {
    color: #d3d4dc;
}

.light-style .landing-footer .footer-title {
    color: #fff;
}

.footer-title {
    color: #fff;
}

.footer-text {
    color: #d3d4dc;
}

@media (max-width: 355px) {
    .first-section-pt {
        margin-block-start: -121px !important;
    }
}

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