<script setup>
import QueueComponent from '@/layouts/components/QueueComponent.vue';
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 patientNotes = ref([])
const headers = [

  { key: 'note', title: 'Notes' },
  { key: 'date', title: 'Date' },
];


// 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 queueComp = ref(null);



const formatDateDate = (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, '-');
};
const historyNotes = computed(async () => {
  console.log('update')
  await store.dispatch('getHistoryPatientNotes', {
    patient_id: localStorage.getItem('patient_id'),
    appointment_id: localStorage.getItem('patient_appiontment_id'),
  })
  let notes = store.getters.getPatientNotes
  for (let data of notes) {
    if (data.note_type == 'Notes') {
      let dataObject = {}
      dataObject.file_url = data.file_url
      dataObject.note = data.note
      dataObject.date = formatDateDate(data.created_at)
      dataObject.id = data.id
      dataObject.agent = data.telemedPro.name
      patientNotes.value.push(dataObject)
    }
  }
  patientNotes.value.sort((a, b) => {
    return b.id - a.id;
  });
  console.log('patientNotes', patientNotes.value)
  store.dispatch('updateIsLoading', false)

});
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 () => {


}

const openCallModel = async (type) => {
  console.log('here')
  if (queueComp.value) {
    console.log(queueComp.value)
    let Calluser = localStorage.getItem('call_user')
    // console.log('Calluser', Calluser)
    queueComp.value.openDialog(JSON.parse(Calluser), type);
  }
};
const handleFormSubmitted = (updatData) => {
  console.log('updatData', updatData)
  for (let data of updatData.notes) {
    if (data.note_type == 'Notes') {
      let foundPatient = patientNotes.value.find(patient => patient.id === data.id);
      if (!foundPatient) {
        let dataObject = {}
        dataObject.note = data.note
        dataObject.file_url = data.file_url
        dataObject.date = formatDateDate(data.created_at)
        dataObject.id = data.id
        dataObject.agent = data.telemedPro.name
        patientNotes.value.push(dataObject)
      }

    }
  }
  patientNotes.value.sort((a, b) => {
    return b.id - a.id;
  });


};
const downloadFile = (fileUrl) => {
  const link = document.createElement('a');
  link.href = fileUrl;

  // Optional: Provide a filename; defaults to the last segment of the path if omitted
  link.download = 'noteFile.png';

  // Append link to the body, click it, and then remove it
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</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>
  <QueueComponent ref="queueComp" :isVisable="false" @formSubmitted="handleFormSubmitted" />
  <v-row class='mb-2'>
    <v-col cols="12" class="text-left " md="6">
      <v-btn color="primary" size="small" @click="openCallModel('Notes')" class="mr-2">
        Add Notes
      </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="text-right cross" md="6">

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

  <VList class="pb-0" lines="two" border v-if="historyNotes" style="border: 0px;">
    <template v-if="patientNotes.length > 0" v-for="(p_note, index) of patientNotes" :key="index">
      <VListItem class="pb-0">
        <VListItemTitle>
          <span class="pb-0">{{ p_note.note }}</span>
          <p class="fs-5 mb-0 pb-0 text-grey"><small class="float-left">{{ p_note.agent }}</small>
            <small class="float-right">
              <span v-if="p_note.file_url" style="font-size: 12px;color:#696cff;top: 0px;
    position: relative;" color="primary">
                <a type="button" @click="downloadFile(p_note.file_url)" title="Download Attachment">
                  <VIcon>mdi-cloud-download</VIcon>
                </a>
              </span> <span v-if="p_note.file_url"> | </span> {{ p_note.date }}

            </small>
          </p>
        </VListItemTitle>
      </VListItem>
      <VDivider v-if="index !== patientNotes.length - 1" />
    </template>
    <template v-else>
      <p class="text-center pt-0 pb-0 mb-0"> No data found</p>
    </template>
  </VList>

</template>

<style lang="scss" scoped>
.v-list-item-title {
  white-space: unset;
}

.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>
