<script setup>
import store from '@/store';
import moment from 'moment';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const getHistory = ref([]);
const doctorAppiontments = ref([]);
const selectedFilter = ref(null);
const currentMonth = ref('');

onMounted(async () => {
    currentMonth.value = moment().format('MMMM') + '(Month to date)';
    await store.dispatch('getHistory')
    getHistory.value = store.getters.getHistory.history;
    console.log("getHistory", getHistory.value);
    store.dispatch('updateIsLoading', false)
})

const filter = [
    {
        value: 'This Month',
        key: 'current_month'
    },
    {
        value: 'Past Month',
        key: '1_month'
    },
    {
        value: 'Past 2 Month from today',
        key: '2_months'
    },
    {
        value: 'Past 3 Month from today',
        key: '3_months'
    },
    {
        value: 'Past 6 Month from today',
        key: '6_months'
    },
    {
        value: 'Past 12 Month from today',
        key: '12_months'
    },

    {
        value: 'All Time',
        key: 'all_time'
    },
];
const patient_name = ref();
const patient_email = ref();
const handleDateInput = async () => {
    getHistory.value = [];
    await store.dispatch('getHistoryFilter', {
        filter: selectedFilter.value,
    })
    getHistory.value = store.getters.getHistoryFilter.patients;
    // patient_name.value = store.getters.getHistoryFilter.patients.patient;
    // patient_email.value = store.getters.getHistoryFilter.patients.patient;
    console.log("getHistoryFilter", getHistory.value);
    store.dispatch('updateIsLoading', false)
}

const search = ref('');
const headers = [
    { align: 'start', key: 'order_id', title: 'Order' },
    { align: 'start', key: 'id', title: 'Appiontment' },
    { key: 'appointment_date', sortable: false, title: 'Date' },
    { key: 'patient_name', title: 'Patient' },

    // { key: 'start_time', title: 'Start Time' },
    // { key: 'end_time', title: 'End Time' },
    // { key: 'duration', title: 'Duration' },
    { key: 'action', title: 'Action' },
];

const formattedHistory = computed(() => {
    return getHistory.value.map(history => ({
        ...history,
        appointment_date: changeFormat(history.appointment_date),
        start_time: changeDateFormat(history.start_time),
        end_time: changeDateFormat(history.end_time),
        duration: totalCallDuration(history.start_time, history.end_time),
    }));
});
function changeDateFormat(dateFormat) {
    console.log("startTimeFormat", dateFormat);
    if (dateFormat) {
        const [datePart, timePart] = dateFormat.split(' '); // Split date and time parts
        const [year, month, day] = datePart.split('-'); // Split date into year, month, and day
        const formattedMonth = parseInt(month).toString(); // Convert month to integer and then string to remove leading zeros
        const formattedDay = parseInt(day).toString(); // Convert day to integer and then string to remove leading zeros
        const formattedDate = `${formattedMonth}-${formattedDay}-${year}`; // Format date as mm-dd-yyyy
        return `${formattedDate} ${timePart}`; // Combine formatted date with original time part
    }
}
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;
}
// function changeFormat(dateFormat) {
//     if (dateFormat) {
//         const dateParts = dateFormat.split('-'); // Assuming date is in yyyy-mm-dd format
//         const year = parseInt(dateParts[0]);
//         const month = String(dateParts[1]).padStart(2, '0'); // Pad single-digit months with leading zero
//         const day = String(dateParts[2]).padStart(2, '0'); // Pad single-digit days with leading zero

//         // 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;
//     }
// }
function totalCallDuration(start_time, end_time) {
    console.log(start_time, end_time);
    const startMoment = moment(start_time);
    const endMoment = moment(end_time);

    // Calculate the duration
    const duration = moment.duration(endMoment.diff(startMoment));
    const hours = duration.hours();
    const thours = `${String(hours).padStart(2, '0')}`;
    const minutes = duration.minutes();
    const tminutes = `${String(minutes).padStart(2, '0')}`;
    const seconds = duration.seconds();
    const tsecond = `${String(seconds).padStart(2, '0')}`;
    let durationText;
    if (hours === 0 && minutes === 0) { //for second
        durationText = ` 00:00:${tsecond}`;
    } else if (hours === 0 && minutes > 0) { //for minutes
        durationText = `00:${tminutes}:${tsecond}`;
    } else if (hours > 0) {  //for hours
        durationText = `${thours}:${tminutes}:${tsecond}`;
    }
    const totalDuration = durationText;
    console.log('Duration:', durationText);
    // You may need to adjust this function based on your actual data structure
    // For example, if you have separate first name and last name properties in each appointment object
    return totalDuration; // For now, just return the first name
}

const historyDetail = (item) => {
    console.log('item', item)
    router.push('/provider/order-detail/' + item.order_id);
}
</script>
<template>
    <VRow>
        <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>
        <VCol cols="12">
            <VCard title="Meeting History">
                <v-card flat>
                    <v-card-title class="d-flex align-center pe-2">
                        <!--<v-select label="Search" v-model="selectedFilter" :items="filter" item-title="value"
                            item-value="key" @update:modelValue="handleDateInput" density="compact"></v-select>
                        <v-text-field v-model="search" prepend-inner-icon="mdi-magnify" density="compact" label="Search"
                            single-line flat hide-details variant="solo-filled"></v-text-field> -->
                        <v-spacer></v-spacer>
                        <v-spacer></v-spacer>
                        <v-spacer></v-spacer>
                    </v-card-title>

                    <v-data-table :headers="headers" :items="formattedHistory">
                        <template #item.order_id="{ item }">
                            <RouterLink :to="{ name: 'provider-order-detail', params: { id: item.order_id } }">
                                #{{ item.order_id }}
                            </RouterLink>
                        </template>
                        <template #item.patient_name="{ item }">
                            <div class="d-flex align-center">
                                <VAvatar size="32" :color="item.profile_picture ? '' : 'primary'"
                                    :class="item.profile_picture ? '' : 'v-avatar-light-bg primary--text'"
                                    :variant="!item.profile_picture ? 'tonal' : undefined">
                                    <VImg v-if="item.profile_picture" :src="item.profile_picture" />
                                    <span v-else>{{ item.patient_name.charAt(0) }}</span>
                                </VAvatar>
                                <div class="d-flex flex-column ms-3">
                                    <RouterLink :to="{ name: 'provider-order-detail', params: { id: item.id } }">
                                        <div class=" font-weight-medium">
                                            {{ item.patient_name }}
                                        </div>
                                    </RouterLink>
                                    <small>{{ item.patient_email }}</small>
                                </div>
                            </div>
                        </template>
                        <template #item.action="{ item }">
                            <IconBtn size="small">
                                <VIcon icon="ri-more-2-line" />
                                <VMenu activator="parent">
                                    <VList>
                                        <VListItem value="view">
                                            <RouterLink
                                                :to="{ name: 'provider-order-detail', params: { id: item.order_id } }"
                                                class="text-high-emphasis">
                                                View
                                            </RouterLink>
                                        </VListItem>

                                    </VList>
                                </VMenu>
                            </IconBtn>
                        </template>

                    </v-data-table>

                </v-card>

            </VCard>
        </VCol>

    </VRow>

</template>
