<script setup>
import { useAppAbility } from '@/plugins/casl/useAppAbility';
import StartOverPupup from '@/views/pages/home/StartOverPupup.vue';
import DefinedSteps from '../layouts/components/DefinedSteps.vue';
import CustomNav from '../layouts/components/navbar-custom.vue';
// import { useAppAbility } from '@/plugins/casl/useAppAbility';
import axios from '@axios';
import {
    emailValidator,
    requiredEmail,
    requiredPassword
} from '@validators';
import { onBeforeMount, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const router = useRouter()
const route = useRoute()
const ability = useAppAbility()
const isMobile = ref(window.innerWidth <= 768);
const emailExist = ref(false)
const isTopLoadingVisible = ref(false);
const isLoadingVisible = ref(false)
const refVForm = ref()
const email = ref()
const password = ref(null)
const isPolicy = ref(false);
const user_role = ref();
const seetingPlanLogo = ref();
const settingSite = ref();
const isPasswordVisible = ref(false)
const canLogin = ref(false)
const inavlid = ref(false);
const InvalidCredential = ref()
const passwordCheck = ref(false)
const products = JSON.parse(localStorage.getItem('cart_products'));
const prescreptionRequired = ref(false)
const errors = ref({
    password: undefined,
    email: undefined,
})
watch(isPolicy, (newVal) => {
    isTopLoadingVisible.value = false;
});
const checkIfMobile = () => {
    isMobile.value = window.innerWidth <= 768;
};
const onSubmit = async () => {

    refVForm.value?.validate().then(async ({ valid: isValid }) => {
        console.log('isValid ', isValid)
        if (isValid) {
            store.dispatch('updateIsTonalSnackbar', false)
            store.dispatch('updateErrorMessage', null)
            if (!canLogin.value) {



                await registerPatient()



            } else {
                passwordCheck.value = false
                await loginPatient()
            }


            // await register()
            // console.log(store.getters.getErrors.email)
            // if (!store.getters.getErrors.email) {
            //     await savePlan()
            //     router.replace(route.query.to && route.query.to != '/register' ? String(route.query.to) : 'book-appointment')
            // }
        }

    })
}

onBeforeMount(async () => {
    products.forEach(product => {
        if (product.is_prescription_required == 1) {

            prescreptionRequired.value = true
        } else {

            prescreptionRequired.value = false
        }
    });
    // grandTotal.value = parseFloat(totalAmount.value) + parseFloat(totalShipping.value)
    store.dispatch('updateCurrentPage', 'pre-register')
    localStorage.setItem('currentPage', 'pre-register')
})
onMounted(async () => {
    window.addEventListener('resize', checkIfMobile);

    let setting = await axios.post('/api/settings', {})
    // console.log(setting.data)
    settingSite.value = setting.data
    seetingPlanLogo.value = '/assets/logo/' + setting.data.logo

    // getLocation()
})
onUnmounted(() => {
});

const registerPatient = async () => {
    errors.value = [];
    store.dispatch('updateIsLoading', true)
    isLoadingVisible.value = true;

    await axios.post('/api/check-email', {
        email: email.value,

    }).then(r => {
        console.log("Reigster", r.data);
        if (r.data.email === "Exist") {
            emailExist.value = true
            canLogin.value = true
            localStorage.setItem('exist', true)
        } else {
            localStorage.setItem('email', email.value)
            localStorage.setItem('exist', false)
            emailExist.value = false
            canLogin.value = false
            passwordCheck.value = true


            if (password.value) {
                localStorage.setItem('password', password.value)
                router.replace(route.query.to && route.query.to != '/pre-register' ? String(route.query.to) : 'register')
            }

        }
        store.dispatch('updateIsLoading', false)
    }).catch(e => {
        store.dispatch('updateIsLoading', false)
        console.log(e.response);
        const { errors: formErrors } = e.response.data.errors;
        errors.value = e.response.data.errors;
        isLoadingVisible.value = false;
        console.error("Error", e.response.data.errors)
    });

};
const loginPatient = async () => {
    store.dispatch('updateIsLoading', true)
    InvalidCredential.value = '';
    isLoadingVisible.value = true;
    axios.post('/api/login-patient', {
        email: email.value,
        password: password.value,
    }).then(r => {
        console.log("Response", r.data, prescreptionRequired.value);
        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', 'register')
        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)
        // if (prescreptionRequired.value)
        //     router.replace(route.query.to && route.query.to != '/pre-register' ? String(route.query.to) : '/additional-information')
        // else
            router.replace(route.query.to && route.query.to != '/pre-register' ? String(route.query.to) : '/checkout')
    }).catch(error => {
        store.dispatch('updateIsLoading', false)
        console.error('Login Error', error)
        inavlid.value = true;
        // if (error.response.data.message)
        //     errors.value.email = error.response.data.message;
        // else
        InvalidCredential.value = "Sorry, that email or password didn't work.";
        // errors.value.email = 'Invalid credentials'
        isLoadingVisible.value = false;
    });

};
const isUserAuthenticate = () => {

    user_role.value = localStorage.getItem('user_role');
    if (user_role.value === 'agent') {
        router.push('/provider/dashboard');
    } else if (user_role.value === 'patient') {
        router.push('/overview');
    } else {
        window.location.href = 'https://hgh.codelfi.com/';
    };
};
const changeEmail = () => {
    canLogin.value = false
    InvalidCredential.value = null
    password.value = null

};
const changeEmailSignUp = () => {
    canLogin.value = false
    passwordCheck.value = false
};
</script>

<template>
    <StartOverPupup :showPopup="store.getters.getShowStartOverPupup"></StartOverPupup>
    <VDialog v-model="store.getters.getIsLoading" 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>
    <!-- <HeaderTopBar></HeaderTopBar> -->
    <!-- <div class="auth-wrapper d-flex align-center justify-center pa-4"> -->
    <VRow><CustomNav :logo='seetingPlanLogo'></CustomNav></VRow>
    <VRow
    style="min-height: 101.7dvh; max-height: 101.7dvh; margin: 0px;"
    :style="isMobile ? { marginTop: '90px' } : { marginTop: '0px' }"
    >
        <VCol cols="12" md="6" class="bg-custom col-order-1"
            :class="isMobile ? '' : 'auth-wrapper d-flex align-center justify-center pa-4'">
            <DefinedSteps></DefinedSteps>
        </VCol>
        <VCol cols="12" md="6" class="bg-custom-color col-order-2"
            :class="isMobile ? '' : 'auth-wrapper d-flex align-center justify-center pa-4'">
            <!-- <div class="auth-wrapper d-flex align-center justify-center pa-4"> -->
            <VCard class="auth-card pa-2 rounded-5" style="" :class="isMobile ? '' : 'card-wid'">
                <VCardItem class="py-2">
                    <VCardText class="p-0">
                        <!-- <VRow>
                            <VCol cols="12" lg="12" md="12" class="pb-4">
                                <div class="text-center mb-2 cursor-pointer"
                                    style="width: 100%;position: relative;display: block; padding-top: 20px;">
                                    <span class="text-center">
                                        <VImg :src='seetingPlanLogo' width="250" height="50" class="logo-img"
                                            @click="isUserAuthenticate" />
                                    </span>
                                </div>
                            </VCol>
                        </VRow> -->
                        <h5 class="text-h5 mb-1 text-left">
                            Welcome! Need Our MD?
                        </h5>
                        <p v-if="canLogin">That's great, you've got an account! Welcome back!</p>
                        <p v-if="!canLogin">You'll need an account. Let get you setup!
                        </p>
                    </VCardText>

                    <VSnackbar v-model="store.getters.getIsTonalSnackbarVisible" :timeout="5000" location="top end"
                        variant="flat" color="red">
                        {{ store.getters.getErrorMessage }}
                    </VSnackbar>
                </VCardItem>
                <VCardText>

                    <VForm ref="refVForm" @submit.prevent="onSubmit">
                        <VRow>

                            <VCol cols="12" md="12" class="pb-0" v-if="canLogin">
                                <div class="float-right">
                                    <span style="color: #b1c3d5;">This is not your email? </span><span><a
                                            class=" cursor-pointer" @click="changeEmail()">(Change)</a></span>
                                </div>

                            </VCol>
                            <VCol cols="12" md="12" class="pb-0" v-if="passwordCheck">
                                <div class="float-right">
                                    <span style="color: #b1c3d5;">This is not your email? </span><span><a
                                            class=" cursor-pointer" @click="changeEmailSignUp()">(Change)</a></span>
                                </div>

                            </VCol>
                            <VCol cols="12" md="12" v-if="canLogin">
                                <VTextField v-model="email" label="Email Address" type="email"
                                    :rules="[requiredEmail, emailValidator]" :error-messages="errors.email"
                                    density="comfortable" :disabled="canLogin" />

                            </VCol>

                            <VCol cols="12" md="12" v-if="!canLogin">
                                <VTextField v-model="email" label="Email Address" type="email"
                                    :rules="[requiredEmail, emailValidator]" :error-messages="errors.email"
                                    density="comfortable" :disabled="passwordCheck" />
                            </VCol>
                            <VCol cols="12" v-if="canLogin">
                                <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>
                            <VCol cols="12" class="pt-0 pb-0" v-if="canLogin">
                                <router-link to="/forgot" class="text-primary underline">Forgot Password?</router-link>

                            </VCol>
                            <VCol cols="12" v-if="passwordCheck">
                                <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>
                        </VRow>

                        <VRow>
                            <VCol class="text-center" cols="12">
                                <p class="error-message" v-if="inavlid">{{ InvalidCredential }}</p>
                                <VBtn v-if="!canLogin" type="submit" class="text-center px-5"
                                    style="background-color: rgb(var(--v-theme-yellow-theme-button)) !important;" block>
                                    Continue
                                </VBtn>
                                <!-- Can Login and proceed -->
                                <VBtn v-if="canLogin" type="submit" class="text-center px-5"
                                    style="background-color: rgb(var(--v-theme-yellow-theme-button)) !important;" block>
                                    Continue
                                </VBtn>
                            </VCol>
                        </VRow>


                        <VRow>
                        </VRow>
                    </VForm>

                </VCardText>
            </VCard>
            <!-- </div> -->
        </VCol>
    </VRow>
    <!-- </div> -->
    <!-- <Footer></Footer> -->
</template>
<style scoped>
@media only screen and (max-width: 768px) {
    .card-wid {
        max-width: 600px !important;
        min-width: auto !important;
    }

    .col-order-1 {
        order: 2;
    }

    .col-order-2 {
        order: 1;
    }
}
@media (min-width: 960px) and (max-width: 1200px){
    .card-wid{
        min-width: auto !important;
    }
}
@media only screen and (min-width: 769px) {
    .col-order-1 {
        order: 1;
    }

    .col-order-2 {
        order: 2;
    }
}

.total-font {
    font-size: 20px;
    margin-bottom: 5px;
}

.bg-custom {
    background: #fffeee;
}

.bg-custom-color {
    background: #f1e7e4;
}

.bg-white bg-change-bk .current-plan {
    border: 2px solid rgb(var(--v-theme-primary));
}

.cut-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-decoration: line-through;
    text-decoration-color: red;
    text-decoration-thickness: 1px;
}

.plan-card {
    margin: 0rem;
    margin-bottom: 0;
}

.card-wid {
    min-width: 600px;
}

.layout-wrapper {
    justify-content: center;
}

.error-message {
    color: #ff2f2f;
    font-size: 15px;
}
</style>

<style>
@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";


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

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

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

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