<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 getPrescriptionHistory = ref([]);
const doctorAppiontments = ref([]);
const selectedFilter = ref(null);
const currentMonth = ref(null);

onMounted(async () => {
    await store.dispatch("getPrescriptionHistory");
    getPrescriptionHistory.value = store.getters.getPrescriptionHistory.history;
    console.log("getPrescriptionHistory", getPrescriptionHistory.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 handleDateInput = async () => {
    getHistory.value = [];
    // await store.dispatch('getHistoryFilter', {
    //     filter: selectedFilter.value,
    // })
    // getHistory.value = store.getters.getHistoryFilter.patients;
    // console.log("getHistoryFilter", getHistory.value);
    // store.dispatch('updateIsLoading', false)
};

const search = ref("");
const headers = [
    // { align: "start", key: "id", title: "Appiontment Id" },
    // { key: "patient_name", title: "Patient" },
    { key: "appointment_date", sortable: false, title: "Date" },
    { key: "start_time", title: "Start Time" },
    { key: "end_time", title: "End Time" },
    { key: "duration", title: "Duration" },
    { key: "action", title: "Action" },
];

const formattedHistory = computed(() => {
    return getPrescriptionHistory.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) {
//     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("/patient/prescription-history/" + item.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="Prescriptions">
                <v-card flat>
                    <v-card-title class="d-flex align-center pe-2">
                        <v-select
                            label="April(Month to date)"
                            v-model="selectedFilter"
                            :items="filter"
                            item-title="value"
                            item-value="key"
                            @update:modelValue="handleDateInput"
                        ></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 v-slot:item.action="{ item }">
                            <VBtn
                                class="text-capitalize text-white"
                                @click="historyDetail(item)"
                                >Detail
                            </VBtn>
                        </template>
                    </v-data-table>
                </v-card>
            </VCard>
        </VCol>
    </VRow>
</template>
