<script setup>
import moment from 'moment';
import { onBeforeMount, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';

const store = useStore();
const router = useRouter();
const route = useRoute();
const editDialog = ref(false);
const deleteDialog = ref(false);
const search = ref('');
const appointmentId = ref('');
const defaultItem = ref({
  id: -1,
  avatar: '',
  name: '',
  email: '',
  dob: '',
  phone_no: '',
});

const editedItem = ref({ ...defaultItem.value });
const editedIndex = ref(-1);
const providerMeetingList = ref([]);
const isLoading = ref(false);

// Status options
const selectedOptions = [
  { text: 'Active', value: 1 },
  { text: 'InActive', value: 2 },
];

const refVForm = ref(null);

// Headers
const headers = [
  // { title: 'Appointment Id', key: 'id' },
  { title: 'Patient', key: 'patient_name' },
  // { key: 'appointment_date', sortable: false, title: 'Date' },
  { key: 'start_time', title: 'Start Time' },
  { key: 'end_time', title: 'End Time' },
  { key: 'duration', title: 'Duration' },
  { title: 'ACTIONS', key: 'actions' },
];

// Utility functions
function changeDateFormat(dateFormat) {
  if (dateFormat) {
    const [datePart, timePart] = dateFormat.split(' ');
    const [year, month, day] = datePart.split('-');
    // const formattedDate = `${parseInt(month)}-${parseInt(day)}-${year}`;
    return `${formattedDate} ${timePart}`;
  }
  return dateFormat;
}

function changeFormat(dateFormat) {
  const [year, month, day] = dateFormat.split('-');
  return `${parseInt(month)}-${parseInt(day)}-${year}`;
}

function totalCallDuration(start_time, end_time) {
  const startMoment = moment(start_time);
  const endMoment = moment(end_time);
  const duration = moment.duration(endMoment.diff(startMoment));
  const hours = String(duration.hours()).padStart(2, '0');
  const minutes = String(duration.minutes()).padStart(2, '0');
  const seconds = String(duration.seconds()).padStart(2, '0');
  
  if (hours === '00' && minutes === '00') {
    return `00:00:${seconds}`;
  } else if (hours === '00') {
    return `00:${minutes}:${seconds}`;
  } else {
    return `${hours}:${minutes}:${seconds}`;
  }
}

// Fetch and process the patient meeting list
const getPatientMeetingList = async () => {
  store.dispatch('updateIsLoading', true);
  await store.dispatch('providerMeetingList', { id: route.params.id });
  store.dispatch('updateIsLoading', false);

  let list = store.getters.getProviderMeetingList;
  providerMeetingList.value = list.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),
  }));
  console.log(list);
};

// Lifecycle hooks
onBeforeMount(() => {});
onMounted(async () => {
  await getPatientMeetingList();
  
});
onUnmounted(() => {});
const historyDetail = (item, value) => {
    console.log('item',item.id ,value)
    if(value == 'notes')
    router.push('/admin/patient/meeting/notes/' + item.patient_id + '/' + item.id);
    if(value == 'prescription')
    router.push('/admin/patient/meeting/prescription/' + item.patient_id + '/' + item.id);
}
const menusVariant = [
  'primary'
];
const options = [
  {
    title: 'Notes',
    key: 'notes',
  },
  {
    title: 'Prescription',
    key: 'prescription',
  },
  
]
</script>

<template>
  <v-row>
    <v-col cols="12" md="12">
      <v-card title="Meetings">
        <v-card-text>
          <v-row>
            <v-col cols="12" offset-md="8" md="4">
              <v-text-field
                v-model="search"
                label="Search"
                placeholder="Search ..."
                append-inner-icon="ri-search-line"
                single-line
                hide-details
                dense
                outlined
              />
            </v-col>
          </v-row>
        </v-card-text>
        <v-data-table
          :headers="headers"
          :items="providerMeetingList"
          :search="search"
          :items-per-page="5"
          class="text-no-wrap"
        >
          <template #item.id="{ item }">{{ item.id }}</template>
          <template #item.duration="{ item }">{{ item.duration }}</template>
          <!-- Actions -->
          <template #item.actions="{ item }">
          <div class="demo-space-x">
          <VMenu
            v-for="menu in menusVariant"
            :key="menu"
          >
            <template #activator="{ props }">
              
                <i class="ri-more-2-line cursor-pointer"  v-bind="props"></i>
              
            </template>

            <v-list>
            <v-list-item
              v-for="opt in options"
              :key="opt.value"
              @click="historyDetail(item, opt.key)"
            >
              {{ opt.title }}
            </v-list-item>
          </v-list>
          </VMenu>
        </div>
            <!-- <div class="d-flex gap-1">
              <VBtn class="text-capitalize text-white" @click="historyDetail(item)"> Detail
                            </VBtn>
            </div> -->
          </template>
        </v-data-table>
      </v-card>  
    </v-col>
  </v-row>
</template>
