<script setup>
import axios from '@axios';
import moment from 'moment';
import CustomNav from '../layouts/components/navbar-custom.vue';
import { onBeforeMount, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const router = useRouter()
const route = useRoute()
const loginuser = ref('');
const firstName = ref('');
const lastName = ref('');
const email = ref('');
const phoneNumber = ref('');
const address = ref('');
const city = ref('');
const state = ref('');
const zip_code = ref('');
const country = ref('');
const dob = ref('')
const gender = ref('')
const marital_status = ref('')
const height = ref('')
const weight = ref('')
const scheduleDate = ref('');
const scheduleTime = ref('');
const timeZone = ref('');
const timeDifference = ref();
const shippingAddress = ref();
const planName = ref('')
const planAmount = ref('')
const list_one_title = ref('')
const list_sub_title = ref('')
const list_two_title = ref('')
const isLoadingVisible = ref(false)
const seetingPlanLogo = ref();
const patient_id = localStorage.getItem('patient_id')
const access_token = localStorage.getItem('access_token');
const products = JSON.parse(localStorage.getItem('cart_products'));
const labKits = JSON.parse(localStorage.getItem('labkits'));
const totalShipping = ref(0)
const totalAmount = ref(0)
const grandTotal = ref(0)
const prescreptionRequired = ref(false)
const productsNames = ref('')
onBeforeMount(async () => {
    products.forEach(product => {
        var price = 0
        if (product.is_prescription_required == 1) {

            prescreptionRequired.value = true
            if (labKits[0].amount)
                price = labKits[0].amount
            product.title = 'LabKit For ' + product.title
            product.price = productTotalPreReq(price)
            totalAmount.value += price;
            console.log('Prescreption Req Price', price)
        } else {

            prescreptionRequired.value = false
            price = parseFloat(product.price);
            product.price = productTotal(product)
            totalAmount.value += product.qty * price;
            console.log('Not Req Price', price)
        }
        const shippingPrice = parseFloat(product.shipping_cost);
        totalShipping.value += product.qty * shippingPrice;

    });
    let options = { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 };
    grandTotal.value = new Intl.NumberFormat('en-US', options).format(parseFloat(totalAmount.value) + parseFloat(totalShipping.value));
    totalAmount.value = new Intl.NumberFormat('en-US', options).format(totalAmount.value);
    totalShipping.value = new Intl.NumberFormat('en-US', options).format(totalShipping.value);
    // grandTotal.value = parseFloat(totalAmount.value) + parseFloat(totalShipping.value)
    store.dispatch('updateIsLoading', true)
    store.dispatch('updateCurrentPage', 'thankyou')
    localStorage.setItem('currentPage', 'thankyou')
    await store.dispatch('getPatientInfo')
    await store.dispatch('getPlanInfo')
    await store.dispatch('getPatientAppointment')
    await store.dispatch('getAdditionalInformation')
    planName.value = store.getters.getPatientPlan.plan_name
    planAmount.value = store.getters.getPatientPlan.plan_amount
    list_one_title.value = localStorage.getItem('list_one_title')
    list_sub_title.value = localStorage.getItem('list_sub_title')
    list_two_title.value = localStorage.getItem('list_two_title')
    firstName.value = store.getters.getPatient.first_name;
    lastName.value = store.getters.getPatient.last_name
    email.value = store.getters.getPatient.email
    phoneNumber.value = store.getters.getPatient.phone_no
    dob.value = store.getters.getPatient.dob
    gender.value = store.getters.getPatient.gender
    marital_status.value = store.getters.getPatient.marital_status
    weight.value = store.getters.getPatient.weight
    height.value = store.getters.getPatient.height

    address.value = store.getters.getShippingInformation.shipping_address1
    city.value = store.getters.getShippingInformation.shipping_city
    state.value = store.getters.getShippingInformation.shipping_state
    zip_code.value = store.getters.getShippingInformation.shipping_zipcode
    country.value = store.getters.getShippingInformation.billing_address1
    shippingAddress.value = (address.value ? address.value + ', ' : '') +
        (city.value ? city.value + ', ' : '') +
        (state.value ? state.value + ' ' : '') +
        (zip_code.value ? zip_code.value + ', ' : '') +
        (country.value ? country.value : '');

    let diffInMinutes = store.getters.getTimeDiff.time_diff;


    // scheduleTime.value = appointmentData.appointment_time;
    const time = moment(store.getters.getBookedAppointment.appointment_time, 'HH:mm:ss');

    // Check if the time is AM or PM
    scheduleTime.value = time.format('HH:mm a');
    timeZone.value = store.getters.getBookedAppointment.timezone;
    timeDifference.value = diffInMinutes;
    // console.log(gender.value);

    let dateString = store.getters.getPatient.dob
    let parts = dateString.split("-");
    dob.value = `${parts[1]}-${parts[2]}-${parts[0]}`;

    const appointment_date = new Date(store.getters.getBookedAppointment.appointment_date);
    const formattedDate = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
    }).format(appointment_date);
    scheduleDate.value = formattedDate;
    store.dispatch('updateIsLoading', false)
})
const productTotalPreReq = (price) => {
    let options = { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 };
    return new Intl.NumberFormat('en-US', options).format(parseFloat(price));
};
const productTotal = (product) => {
    let options = { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 };
    return new Intl.NumberFormat('en-US', options).format(product.qty * parseFloat(product.price));
};
onMounted(async () => {
    let setting = await axios.post('/api/settings', {})
    console.log(setting.data)
    seetingPlanLogo.value = '/assets/logo/' + setting.data.logo
})

const continueFun = () => {

    store.dispatch('updateIsLoading', true)
    // if (!dob.value || !gender.value || !marital_status.value || !height.value || !weight.value) {
    //     console.log('here', dob.value, gender.value, marital_status.value, height.value, weight.value)
    //     localStorage.setItem('profileCompleted', '0')
    // }
    localStorage.setItem('access_token', access_token)
    localStorage.setItem('isLogin', 'true')
    router.replace(route.query.to && route.query.to != '/thankyou' ? String(route.query.to) : '/order-detail/' + localStorage.getItem('cart_id'))
}

</script>

<template>
    <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>
    <VRow><CustomNav :logo='seetingPlanLogo'></CustomNav></VRow>
    <VRow
    style="min-height: 100dvh; margin: 0px;"
    :style="isMobile ? { marginTop: '90px' } : { marginTop: '60px' }"
    >
        <VCol cols="12" md="12" class="bg-custom-color col-order-2"
            :class="isMobile ? '' : 'auth-wrapper d-flex align-center justify-center pa-4'">
            <VCard class="auth-card pa-2 rounded-5 regbx" style="" :class="isMobile ? '' : 'card-wid'">
                <VCardItem class="justify-center mb-8">
                    <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>
                <VRow>
                    <VRow class="bg-white">
                        <VCol cols="12 pt-3">
                            <div class="px-4 pl-4 pr-4">
                                <!-- <h4 class="mb-3">Your Lab Test Kit is on its Way.</h4>
                                <p>Congratulations! Your order has been placed successfully.
                                    You can expect to receive the kit at the shipping address you provided within
                                    the next 5-7 business
                                    days.</p>

                                <p>


                                    All future blood testing and associated costs will be included in your monthly
                                    subscription fee.
                                    Next Steps
                                    Once you receive the lab test kit, please follow the enclosed instructions
                                    carefully to
                                    collect and return your blood sample. The kit will include a 2-day return
                                    shipping label for your convenience. Your testing results will be securely sent
                                    to your doctor, and your doctor will review them. You will be notified about the
                                    next steps in your treatment plan.





                                </p>
                                <p>To continue your treatment journey and ensure uninterrupted access to
                                    our services, Please click the "View Order" button below to see your order details.
                                </p> -->
                                <p>
                                    Thankyou for booking your telehealth visit with us. Please keep an eye on your email for
further instructions, In case you have any questions, please reach out to support at
<a href="mailto:support@peptidewebmd.com">support@peptidewebmd.com</a> or refer to the FAQs.
                                </p>
                            </div>
                        </VCol>
                        <VCol cols="12 pt-3 mb-4" class="text-center">
                            <!-- <RouterLink to="/review-appointment"> -->
                            <VBtn class="text-capitalize" @click="continueFun" title="Click here to view order details"
                                style="background-color: rgb(var(--v-theme-yellow-theme-button)) !important;">
                                <b>View Order</b>
                            </VBtn>
                            <!-- </RouterLink> -->

                        </VCol>
                    </VRow>
                </VRow>
            </VCard>
        </VCol>
    </VRow>
</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 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: rgb(var(--v-theme-yellow));
}

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

.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 {
    max-width: 600px;
}

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

.error-message {
    color: #ff2f2f;
    font-size: 15px;
}
</style>
<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;
}

.bg-custom {
    background: rgb(var(--v-theme-yellow));
}

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

.cut-text {
    white-space: nowrap;
    /* Prevents text from wrapping */
    overflow: hidden;
    /* Hides any content that overflows the container */
    text-overflow: ellipsis;
    /* Displays an ellipsis (...) to represent the clipped text */
    // width: 100px;
    text-decoration: line-through;
    text-decoration-color: red;
    /* Set the color of the line */
    text-decoration-thickness: 1px;
    /* Adjust the width as needed */
}

.logo-img {
    display: block;
    position: relative;
    margin: 0 auto;
}
</style>
