<script setup>
import { useRouter } from 'vue-router';
import { useTheme } from 'vuetify';
import { useStore } from 'vuex';
const router = useRouter()
const store = useStore()
const isMobile = ref(window.innerWidth <= 768);
const prescriptionModelForm = ref(false)
const search = ref('');
const loading = ref(true);
const page = ref(1);
const itemsPerPage = ref(10);
const pageCount = ref(0);
const form = ref(null);

const headers = ref([
    { title: 'Patient Name', key: 'name' },
    { title: 'Lab Kit', key: 'testName' },
    { title: 'Address', key: 'address' },

    { title: 'Date', key: 'date' },
    { title: 'Status', key: 'status' },
    // { title: 'Actions', key: 'actions', sortable: false },
]);
const labOrders = ref([
]);
const getStatusColor = (status) => {
    switch (status) {
        case 'pending':
            return 'warning'; // Use Vuetify's warning color (typically yellow)
        case 'shipped':
            return '#45B8AC'; // Use Vuetify's primary color (typically blue)
        case 'delivered':
            return 'green';
        case 'returned':
            return 'red';
        case 'results':
            return 'blue';
        default:
            return 'grey'; // Use Vuetify's grey color for any other status
    }
};
const openDialog = () => {
    state.addLabOrder = true
}

const state = reactive({
    addLabOrder: false,
    selectedTestKitId: null,
    valid: false,
    testKits: [],
});

const testKits = computed(async () => {
    let Calluser = localStorage.getItem('call_user')
    let patient = JSON.parse(Calluser)
    await store.dispatch('getLabKitProductList', {})
    console.log(store.getters.getLabOrderProductList)

    state.testKits = store.getters.getLabOrderProductList
});

const getFieldRules = (value, message) => {
    return [(v) => !!v || message || `Field is required`];
};

const storeTestKit = async () => {
    let Calluser = localStorage.getItem('call_user')
    let patient = JSON.parse(Calluser)
    loading.value = true
    await store.dispatch('saveLabOrderProductList', {
        labkit: state.selectedTestKitId,
        patient_id: patient.id
    })

    console.log('Selected Test Kit:', state.selectedTestKitId);
    await store.dispatch('getLabOrderList', {
        patient_id: patient.id,
    })
    labOrders.value = [];
    let testKitOrder = store.getters.getLabOrderKitAgent
    for (let data of testKitOrder) {
        let dataObject = {}
        dataObject.name = data.name
        dataObject.address = data.address
        dataObject.total_amount = data.total_amount
        dataObject.shipping_amount = data.shipping_amount
        dataObject.status = data.status
        dataObject.phone = data.phone
        dataObject.date = formatDate(data.date)
        dataObject.email = data.email
        dataObject.testName = data.testName
        dataObject.actions = ''
        dataObject.id = data.id
        labOrders.value.push(dataObject)


    }

    labOrders.value.sort((a, b) => {
        return b.id - a.id;
    });
    state.addLabOrder = false;
    state.selectedTestKitId = ''
    loading.value = false
};
const laborderList = computed(async () => {

    let Calluser = localStorage.getItem('call_user')
    let patient = JSON.parse(Calluser)
    await store.dispatch('getLabOrderList', {
        patient_id: patient.id,
    })
    labOrders.value = [];
    let testKitOrder = store.getters.getLabOrderKitAgent
    for (let data of testKitOrder) {
        let dataObject = {}
        dataObject.name = data.name
        dataObject.address = data.address
        dataObject.total_amount = data.total_amount
        dataObject.shipping_amount = data.shipping_amount
        dataObject.status = data.status
        dataObject.phone = data.phone
        dataObject.date = formatDate(data.date)
        dataObject.email = data.email
        dataObject.testName = data.testName
        dataObject.actions = ''
        dataObject.id = data.id
        labOrders.value.push(dataObject)


    }


    labOrders.value.sort((a, b) => {
        return b.id - a.id;
    });
    console.log('patientNotes', labOrders.value)
    store.dispatch('updateIsLoading', false)
    loading.value = false
});


// Components
import { computed } from 'vue';
const vuetifyTheme = useTheme()
const userRole = localStorage.getItem('user_role'); // Fetch user role from local storage
const isAgent = computed(() => userRole.toLowerCase() === 'agent');




const formatDate = (date) => {
    const messageDate = new Date(date);
    const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    return messageDate.toLocaleDateString('en-US', options).replace(/\//g, '-');
};


onMounted(async () => {
    const navbar = document.querySelector('.layout-navbar');
    const callDiv = document.querySelector('.layout-page-content');
    if (navbar) {
        navbar.style.display = 'block';
    }
    if (callDiv)
        callDiv.style.padding = '1.5rem';
    console.log("router", store.getters.getCurrentPage)
    // if (userRole === 'agent') {
    //   await store.dispatch('getHistoryPatientNotes')
    //   let notes = store.getters.getPatientNotes
    //   for(let data of notes ){
    //     if(data.note_type=='Notes'){
    //       let dataObject = {}
    //       dataObject.note=data.note
    //       dataObject.date=formatDateDate(data.created_at)
    //       dataObject.id=data.id
    //       patientNotes.value.push(dataObject)
    //     }
    //   }
    //   patientNotes.value.sort((a, b) => {
    //     return b.id - a.id;
    //   });
    //   console.log('patientNotes', patientNotes.value)
    //   loading.value = false;
    // }
    window.addEventListener('resize', checkMobile);

});

const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768;
};
const openNotes = async () => {


}






</script>

<template>


    <v-row class='mb-2'>
        <v-col cols="12" class="text-left " md="12">
            <v-btn color="primary" size="small" @click="openDialog()" class="mr-2">
                <v-icon>mdi-plus</v-icon> Add Lab Order
            </v-btn>
            <v-btn color="primary" size="small" class="mr-2"><v-icon start icon="tabler-report-medical"></v-icon> GLP-1
                Lab
                Order</v-btn>
            <v-btn color="primary" size="small"><v-icon start icon="tabler-report-medical"></v-icon> TRT Lab
                order</v-btn>
            <!-- <v-btn color="primary" small @click="openCallModel('Request For Documents')">
          <v-icon>mdi-plus</v-icon> Request For Docs
        </v-btn> -->
        </v-col>
        <!-- <v-col cols="12" :class="isMobile ? 'text-left' : 'text-right'" md="3">

    </v-col>
    <v-col cols="12" class="text-left" md="3">

    </v-col> -->
    </v-row>

    <v-row>
        <v-col cols="12" md="12" v-if="laborderList">
            <v-data-table :headers="headers" :items="labOrders" :search="search" :loading="loading" :page.sync="page"
                :items-per-page.sync="itemsPerPage" @page-count="pageCount = $event" class="elevation-1">
                <template v-slot:top>
                    <v-toolbar flat :height="30">
                        <v-toolbar-title>Lab Kits</v-toolbar-title>
                        <v-divider class="mx-4" inset vertical></v-divider>
                        <v-spacer></v-spacer>
                        <v-text-field v-model="search" label="Search" single-line hide-details></v-text-field>
                    </v-toolbar>
                </template>
                <template v-slot:item.status="{ item }">
                    <v-chip :color="getStatusColor(item.status)" label size="small" variant="text">
                        {{ item.status }}
                    </v-chip>
                </template>
                <!-- <template v-slot:item.actions="{ item }">
          <v-btn v-if="item.status === 'In Progress'" color="success" size="small" class="mr-2"
            @click="completeOrder(item.id)">
            Complete
          </v-btn>
          <v-btn v-if="item.status === 'In Progress'" color="error" size="small" @click="cancelOrder(item.id)">
            Cancel
          </v-btn>
        </template> -->
            </v-data-table>
        </v-col>
    </v-row>



    <v-dialog v-model="state.addLabOrder" max-width="400">
        <v-card>
            <v-card-title>Add Lab Kit</v-card-title>
            <v-card-text>
                <v-form ref="form" v-model="state.valid" class="mt-1">
                    <v-row v-if="testKits">
                        <v-col cols="12" md="12">
                            <v-autocomplete label="Test Kit" v-model="state.selectedTestKitId" style="column-gap: 0px;"
                                :items="state.testKits" item-title="name" item-value="id"
                                :rules="getFieldRules('', 'Test Kit is required')"></v-autocomplete>
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="primary" text @click="state.addLabOrder = false">Cancel</v-btn>
                <v-btn color="primary" @click="storeTestKit" :disabled="!state.valid">Save</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>

</template>

<style lang="scss" scoped>
.hidden-component {
    display: none
}

.meta-key {
    border: thin solid rgba(var(--v-border-color), var(--v-border-opacity));
    border-radius: 6px;
    block-size: 1.5625rem;
    line-height: 1.3125rem;
    padding-block: 0.125rem;
    padding-inline: 0.25rem;
}

::v-deep .custom-menu {
    position: relative;
}

::v-deep .custom-menu::before {
    content: "" !important;
    position: absolute !important;
    transform: translateY(-50%);
    top: 50% !important;
    left: -8px !important;
    border-left: 8px solid transparent !important;
    border-right: 8px solid transparent !important;
    border-bottom: 8px solid #fff !important;
}



// Styles for the VList component


.more .v-list-item-title {
    color: rgb(106 109 255);
}

.more .menu-item:hover {
    cursor: pointer;
}

.slide-enter-active,
.slide-leave-active {
    transition: transform 0.3s ease;
}

.slide-enter,
.slide-leave-to {
    transform: translateX(-100%);
}

.start-call-btn {
    opacity: 0;
    display: none;
    transition: opacity 0.3s ease;
}

.button_margin {
    margin: 2px;
}

.dialog_padding {
    padding: 5px;

}



.custom-menu .v-menu__content {
    background-color: #333;
    color: #fff;
    border-radius: 4px;
    padding: 8px 0;
}

.user-info {
    display: flex;
    flex-direction: column;
    transition: opacity 0.3s ease;
}

.list-item-hover {
    transition: background-color 0.3s ease;

    &:hover {
        background-color: rgba(var(--v-theme-primary), 0.1);

        .start-call-btn {
            opacity: 1;
            display: block;
            position: relative;
            left: -35px;
        }

        .user-info {
            opacity: 0;
            display: none;
        }
    }
}

.pop_card {

    overflow: hidden !important;
    padding: 10px;
}

.v-overlay__content {

    max-height: 706.4px;
    max-width: 941.6px;
    min-width: 24px;
    --v-overlay-anchor-origin: bottom left;
    transform-origin: left top;
    top: 154.4px !important;
    left: 204px !important;


}

.button_margin {
    margin-top: 10px;
    font-size: 10px;
}

/* Responsive Styles */
@media screen and (max-width: 768px) {
    .pop_card {
        max-width: 100%;
        margin: 0 auto;
    }
}

.container_img {
    display: flex;
    flex-direction: column;
    width: 100%;
    align-items: center;
}

.image {
    order: 2;
    /* Change the order to 2 in mobile view */
}

.text {
    order: 1;
    /* Change the order to 1 in mobile view */
}

/* Media query for mobile view */
@media (max-width: 768px) {
    .container_img {
        flex-direction: row;
        margin-top: 10px;
    }

    .button_margin_mobile {
        width: 100%;
    }

    .image {
        width: 20%;
        padding: 0 10px;
    }

    .text {
        width: 80%;
        /* Each takes 50% width */
        padding: 0 10px;
        /* Optional padding */
    }

}

::-webkit-scrollbar {
    width: 10px;
    /* Width of the scrollbar */
}

/* Track */
::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* Color of the track */
}

/* Handle */
::-webkit-scrollbar-thumb {
    background: #888;
    /* Color of the handle */
    border-radius: 5px;
    /* Roundness of the handle */
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
    background: #555;
    /* Color of the handle on hover */
}

/* Container for the content */
.scroll-container {
    max-height: 191px;
    /* Maximum height of the scrollable content */
    overflow-y: scroll;
    /* Enable vertical scrolling */
}

/* Content within the scroll container */
.scroll-content {
    padding: 20px;
}

/* Example of additional styling for content */
.scroll-content p {
    margin-bottom: 20px;
}

.cross button {

    padding: 0px;
    margin: 0px;
    /* font-size: 10px; */
    background: none;
    border: none;
    box-shadow: none;
    height: 23px;

}

.v-data-table-header {
    display: table-header-group;
}
</style>
