<script setup>
import TreatmentPlan from '@/views/pages/overview/treatment-plan.vue';
import axios from '@axios';
import moment from 'moment-timezone';
// import HeathCare from '@images/pages/healthcare-wellness-wellbeing-first-aid-box-word-graphic.jpg';
const patient_id = localStorage.getItem('patient_id')
const access_token = localStorage.getItem('access_token');
const isLoadingVisible = ref(false);
const loginuser = ref('');
const scheduleDate = ref('');
const scheduleTime = ref('');
const timeZone = ref('');
const timeDifference = ref();
const timeUntilMeeting = ref('');
const shipmentAddress = ref(null);
const firstName = ref('')
const lastName = ref('')
const email = ref('')
const phone = ref('')
const dob = ref('')
const address = ref('')
const apt = ref('')
const city = ref('')
const state = ref('')
const zipcode = ref('')
const callEnd = ref('');
onMounted(async () => {
    // localStorage.setItem('isLogin', true);
    await appointmentDetails()
    await getPatientInfo()
});

const appointmentDetails = async () => {

    isLoadingVisible.value = true;
    axios.post('/api/agent-last-appointment-detail/' + patient_id, {
        headers: {
            'Authorization': `Bearer ${access_token}`,
        }
    })
        .then(response => {
            console.log('Response Last APPIONT:', response.data);
            if (response.data) {
                let diffInMinutes = response.data.time_diff;
                let appointmentData = response.data.appointment
                let patientData = response.data.patient
                loginuser.value = patientData.first_name + ' ' + patientData.last_name;
                timeZone.value = appointmentData.timezone;
                // const time = appointmentData.appointment_time;
                // scheduleTime.value = moment.tz(time, "HH:mm:ss", timeZone.value).format("hh:mm A");
                // scheduleTime.value = appointmentData.appointment_time;
                // timeZone.value = appointmentData.timezone;
                callEnd.value = appointmentData.end_time;
                // timeDifference.value = diffInMinutes;
                let appointmentDate = convertUtcDateTimeToLocal(appointmentData.appointment_date, appointmentData.appointment_time, 'date')
                let appointmentTime = convertUtcDateTimeToLocal(appointmentData.appointment_date, appointmentData.appointment_time, 'time')
                timeDifference.value = relativeTimeFromDate(appointmentDate, appointmentTime)
                scheduleDate.value = moment(appointmentDate, "YYYY-MM-DD").format("MMMM DD, YYYY")
                scheduleTime.value = moment(appointmentTime, "HH:mm:ss").format("hh:mm A");
                console.log(scheduleTime.value);
                // const appointment_date = new Date(appointmentData.appointment_date);
                // const formattedDate = new Intl.DateTimeFormat('en-US', {
                //     year: 'numeric',
                //     month: 'long',
                //     day: 'numeric',
                // }).format(appointment_date);
                // console.log('formattedDate', formattedDate)
                // scheduleDate.value = formattedDate;

                shipmentAddress.value = (appointmentData.shipping_address1 ? appointmentData.shipping_address1 + ', ' : '') +
                    (appointmentData.shipping_city ? appointmentData.shipping_city + ', ' : '') +
                    (appointmentData.shipping_state ? appointmentData.shipping_state + ' ' : '') +
                    (appointmentData.shipping_zipcode ? appointmentData.shipping_zipcode + ', ' : '') +
                    (patientData.country ? patientData.country : '');
                isLoadingVisible.value = false;
            } else {
                isLoadingVisible.value = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
};
const relativeTimeFromDate = (dateString, timeString) => {
    // Ensure the input is treated as local time explicitly
    const eventDateTime = new Date(dateString + "T" + timeString);

    // Get the current date and time
    const now = new Date();

    // Calculate the difference in milliseconds between the event time and now
    const diffMs = eventDateTime - now;

    // Convert the difference to an absolute value
    const absDiffMs = Math.abs(diffMs);

    // Calculate differences in days, hours, and minutes
    const minutes = Math.floor(absDiffMs / 60000) % 60;
    const hours = Math.floor(absDiffMs / 3600000) % 24;
    const days = Math.floor(absDiffMs / 86400000);

    // Determine the appropriate suffix based on whether the date is in the future or past
    const suffix = diffMs < 0 ? " ago" : " left";

    // Result formulation based on the above logic
    if (days > 0) {
        return `${days} day${days > 1 ? 's' : ''}${suffix}`;
    } else {
        // Compose hours and minutes
        let result = [];
        if (hours > 0) {
            result.push(`${hours} hour${hours > 1 ? 's' : ''}`);
        }
        if (minutes > 0) {
            result.push(`${minutes} minute${minutes > 1 ? 's' : ''}`);
        }
        if (result.length === 0) {
            return 'just now';
        }
        return result.join(' ') + suffix;
    }
}
const convertUtcDateTimeToLocal = (utcDate, utcTime, type) => {
    const utcDateTime = `${utcDate}T${utcTime}Z`;  // Use Z to denote UTC timezone explicitly
    const momentObj = moment.utc(utcDateTime).local();  // Convert UTC to local time

    if (type === 'date') {
        return momentObj.format('YYYY-MM-DD');  // Return local date
    } else if (type === 'time') {
        return momentObj.format('HH:mm:ss');  // Return local time
    } else {
        throw new Error("Invalid type specified. Use 'date' or 'time'.");
    }
};
const getPatientInfo = async () => {
    isLoadingVisible.value = true;
    await axios.post('/api/get-patient-detail/' + patient_id, {
        headers: {
            'Authorization': `Bearer ${access_token}`,
        }
    })
        .then(response => {
            console.log('Response:', response.data);

            firstName.value = response.data.patient.first_name
            lastName.value = response.data.patient.last_name
            email.value = response.data.patient.email
            dob.value = changeFormat(response.data.patient.dob)
            phone.value = response.data.patient.phone_no
            address.value = (response.data.patient.address ? response.data.patient.address + ', ' : '') +
                (response.data.patient.city ? response.data.patient.city + ', ' : '') +
                (response.data.patient.state ? response.data.patient.state + ' ' : '') +
                (response.data.patient.zip_code ? response.data.patient.zip_code + ', ' : '') +
                (response.data.patient.country ? response.data.patient.country : '');
            isLoadingVisible.value = false;

        })
        .catch(error => {
            isLoadingVisible.value = false;
            console.log('Error:', error);
        });
}

function changeFormat(dateFormat) {
    const dateParts = dateFormat.split('-'); // Assuming date is in yyyy-mm-dd format
    const year = parseInt(dateParts[0]);
    const month = parseInt(dateParts[1]); // No need for padding
    const day = parseInt(dateParts[2]); // No need for padding

    // Create a new Date object with the parsed values
    const date = new Date(year, month - 1, day); // Month is zero-based in JavaScript Date object

    // Format the date as mm-dd-yyyy
    const formattedDate = month + '-' + day + '-' + date.getFullYear();

    return formattedDate;
}



</script>

<template>
    <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>
    <VRow>
        <VCol cols="12" md="8">
            <TreatmentPlan :iscallEnd="callEnd" :date="scheduleDate" :time="scheduleTime" :timezone="timeZone"
                :timeDiff="timeDifference" :showShipment="shipmentAddress" />
        </VCol>
        <VCol cols="12" md="4">
            <VCard class="mb-4">
                <VCardText>

                    <h5 class="mt-2 mb-2">ABOUT</h5>

                    <VList class="card-list text-medium-emphasis mb-2">
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-account" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <!-- <span class="font-weight-medium me-1">Full Name:</span> -->
                                <span>{{ firstName }} {{ lastName }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-email" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <!-- <span class="font-weight-medium me-1">Email:</span> -->
                                <span>{{ email }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-calendar" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <!-- <span class="font-weight-medium me-1">DOB:</span> -->
                                <span>{{ dob }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-phone" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <!-- <span class="font-weight-medium me-1">Phone:</span> -->
                                <span>{{ phone }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-address-marker" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <!-- <span class="font-weight-medium me-1">Address:</span> -->
                                <span>{{ address }}</span>
                            </VListItemTitle>
                        </VListItem>
                    </VList>
                    <!-- <VDivider></VDivider> -->

                    <!-- <h5 class="mt-2 mb-2"></h5> -->

                    <VList class="card-list text-medium-emphasis">

                    </VList>


                </VCardText>
            </VCard>
        </VCol>

    </VRow>
</template>
<style>
.v-list-item-title {
    white-space: inherit !important;
    ;
}
</style>
