<script setup>
import { requiredConfirm, requiredPassword } from '@/@core/utils/validators';
import { useAppAbility } from '@/plugins/casl/useAppAbility';
import axios from '@axios';
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const ability = useAppAbility()
const errors = ref({
    new_password: undefined,
    confirm_passowrd: undefined,

})

const seetingPlanLogo = ref();
const inavlid = ref(false);
const InvalidCredential = ref()
const isLoadingVisible = ref(false)

const isNewPasswordVisible = ref(false)
const isConfirmPasswordVisible = ref(false)
const isPolicy = ref(false)
const isDisabled = ref(true)
const isDialogVisible = ref(false)
const refVForm = ref()
const newPassword = ref(null)
const confirmPassword = ref(null)
const email = ref()
const isContent = ref()
const emailError = ref(false);
const errorMessage = ref(false);
const emailMessage = ref('');
const succesMessage = ref('');
const isSuccess = ref(false);
const isFail = ref(false);
const isPaswordUpdated = ref(true);
const isUpdatedPassword = ref(false);
const isResetCard = ref(true);
const matchPasswordsValidator = (value) => {
    if (value !== newPassword.value) {
        errors.confirm_passowrd = ['Passwords do not match'];
        return 'Passwords do not match';
    }
    return true;
}
const props = defineProps(['token']);
const token = props.token;
onMounted(async () => {
    console.log("token", token);
    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
})
const onSubmit = () => {

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

const resetPassword = () => {
    // emailError.value = false;
    // emailMessage.value = '';
    isLoadingVisible.value = true;
    console.log("token", token);
    axios.post(`/api/password-reset?token=${token}`, {
        password: newPassword.value,
        confirm: confirmPassword.value
    }).then(r => {
        console.log("Response", r.data.msg);
        const status = r.data.status;
        if (status && status == 'error') {
            isFail.value = true;
            errorMessage.value = r.data.msg;
            isLoadingVisible.value = false;
        } else {
            succesMessage.value = r.data.msg;
            isSuccess.value = true;
            isResetCard.value = false;
            isUpdatedPassword.value = true;

            isPaswordUpdated.value = false;
            isLoadingVisible.value = false;
        }
    }).catch(error => {
        console.log('error', error.response.data.message);
        // emailMessage.value = error.response.data.message;
        // if (emailMessage.value)
        //     emailError.value = true;
        // isLoadingVisible.value = false;
    });

};
const textField = () => {
    emailError.value = false;
    emailMessage.value = '';
    isSuccess.value = false;
    succesMessage.value = '';
}

</script>

<template>
    <!-- <HeaderTopBar></HeaderTopBar> -->
    <div class="auth-wrapper d-flex align-center justify-center">
        <VCard class="auth-card pt-0 rounded-5" max-width="320" v-if="isResetCard">
            <VCardText>
                <div class="text-center mb-2 cursor-pointer"
                    style="width: 100%;position: relative;display: block; padding-top: 5px;">
                    <span class="text-center">
                        <VImg :src='seetingPlanLogo' width="250" height="50" class="logo-img"
                            @click="isUserAuthenticate" />
                    </span>
                    <h5 class="mb-2 mt-2">
                        Reset Password
                    </h5>
                    <span v-if="isSuccess" class="text-success text-center">{{ succesMessage }}</span>
                </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 v-if="isPaswordUpdated">

                <VForm ref="refVForm" @submit.prevent="onSubmit">
                    <VRow>
                        <VCol cols="12">
                            <VTextField v-model="newPassword" :type="isNewPasswordVisible ? 'text' : 'password'"
                                :append-inner-icon="isNewPasswordVisible ? 'bx-show' : 'bx-hide'" label="New Password"
                                placeholder="············"
                                @click:append-inner="isNewPasswordVisible = !isNewPasswordVisible"
                                :rules="[requiredPassword]" :error-messages="errors.new_password" density="compact" />
                            <!-- <p v-if="emailError" class="email-error error">{{ emailMessage }}</p> -->
                        </VCol>

                        <VCol cols="12">
                            <VTextField v-model="confirmPassword" :type="isConfirmPasswordVisible ? 'text' : 'password'"
                                :append-inner-icon="isConfirmPasswordVisible ? 'bx-show' : 'bx-hide'"
                                label="Re-enter Password" placeholder="············"
                                @click:append-inner="isConfirmPasswordVisible = !isConfirmPasswordVisible"
                                :rules="[requiredConfirm, matchPasswordsValidator]"
                                :error-messages="errors.confirm_passowrd" density="compact" />
                            <!-- <p v-if="emailError" class="email-error error">{{ emailMessage }}</p> -->
                        </VCol>


                        <VCol cols="12">
                            <p class="error-message" v-if="isFail">{{ errorMessage }}</p>
                            <!-- login button -->
                            <VBtn block type="submit" class="text-capitalize">
                                Set New Password
                            </VBtn>
                        </VCol>


                    </VRow>
                </VForm>

            </VCardText>
            <VCol cols="12" class="text-center px-0 py-0 mb-3">

                <RouterLink to="/login">
                    <h>Return to Login</h>
                </RouterLink>
            </VCol>
        </VCard>
        <VCard width="400" v-if="isUpdatedPassword">
            <VCardText class="text-center">
                <div class="text-center mb-2 cursor-pointer"
                    style="width: 100%;position: relative;display: block; padding-top: 5px;">
                    <span class="text-center">
                        <VImg :src='seetingPlanLogo' width="250" height="50" class="logo-img"
                            @click="isUserAuthenticate" />
                    </span>
                </div>
            </VCardText>
            <v-card-text class="text-center">
                <span v-if="isSuccess" class="text-center">{{ succesMessage
                    }}</span>
            </v-card-text>
            <VCardText class="text-center">
                <RouterLink to="/login">
                    Return to Login
                </RouterLink>
            </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";

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

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

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

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>
