<script setup>
import moment from 'moment-timezone';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const router = useRouter()
const route = useRoute()
const isMeetingEnable = ref(false);
const isMeetingEnd = ref(true);
const meetingInFuture = ref(true);
const scheduleTime = ref();
const scheduleDate = ref();
const timeDifference = ref();
const callEnd = ref('');
const timeZone = ref();
const scheduleData = ref([]);
const expanded = ref([]);
const panel = ref(0)
const appId = ref();
const dessertHeaders = ref(
  [
    // { title: '', key: 'data-table-expand' },
    {
      title: 'Order ID',
      align: 'start',
      sortable: false,
      key: 'name',
    },
    { title: 'Date', key: 'calories' },
    { title: 'Product', key: 'fat' },

  ]
);
const desserts = ref([
  {
    name: '24',
    calories: 'July 04, 2024 02:00 AM',
    fat: 2

  },

]);
onMounted(async () => {
  await fetchApiData();
})
const fetchApiData = async () => {
  store.dispatch('updateIsLoading', true)
  await store.dispatch('getPatientAppointment')
  appId.value = store.getters.getBookedAppointment.appiontmentId;
  let appointmentDate = convertUtcDateTimeToLocal(store.getters.getBookedAppointment.appointment_date, store.getters.getBookedAppointment.appointment_time, 'date')
  let appointmentTime = convertUtcDateTimeToLocal(store.getters.getBookedAppointment.appointment_date, store.getters.getBookedAppointment.appointment_time, 'time')
  // timeDifference.value = relativeTimeFromDate(appointmentDate, appointmentTime)
  scheduleDate.value = moment(appointmentDate, "YYYY-MM-DD").format("MMMM DD, YYYY")
  scheduleTime.value = moment(appointmentTime, "HH:mm:ss").format("hh:mm A");
  timeZone.value = store.getters.getBookedAppointment.timezone;

  console.log("sch", scheduleDate.value, scheduleTime.value);
  // scheduleDate.value = formatDateToISO(store.getters.getBookedAppointment.appointment_date);
  // scheduleTime.value = store.getters.getBookedAppointment.appointment_time;
  callEnd.value = store.getters.getBookedAppointment.end_time;
  meetingInFuture.value = isDateTimeInFuture(scheduleDate.value, scheduleTime.value);
  iscallEnd();
  store.dispatch('updateIsLoading', false)
}

const iscallEnd = async () => {
  if (callEnd && !meetingInFuture.value) {
    isMeetingEnable.value = false;
    console.log('Bth Conditin');
  }
  else if (callEnd) { // Call has been end
    isMeetingEnable.value = false;

    console.log('callEnd');
  } else if (!meetingInFuture.value) { // Patient can Join Meeting
    isMeetingEnable.value = true;
    console.log('timeDiff');
  } else { // Call has been end
    console.log('else');
    isMeetingEnable.value = false;

  }
  await nextTick();
  // isAgentCall();
};

const isDateTimeInFuture = (dateString, timeString) => {
  // Combine the date and time strings into a datetime string
  const dateTimeString = dateString + " " + timeString;

  // Convert the datetime string into a Date object
  const eventDateTime = new Date(dateTimeString);

  // Get the current date and time
  const now = new Date();

  // Compare the eventDateTime with the current date and time
  return eventDateTime > now;
};
const convertUtcDateTimeToLocal = (utcDate, utcTime, type) => {
  const utcDateTime = `${utcDate}T${utcTime}Z`;  // Use Z to denote UTC timezone explicitly
  const momentObj = moment.utc(utcDateTime).local();  // Convert UTC to local time

  if (type === 'date') {
    return momentObj.format('YYYY-MM-DD');  // Return local date
  } else if (type === 'time') {
    return momentObj.format('HH:mm:ss');  // Return local time
  } else {
    throw new Error("Invalid type specified. Use 'date' or 'time'.");
  }
};
</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>
  <VCol cols="12" class="px-0">

    <VCardTitle class="my-1">Upcoming Appiontments</VCardTitle>

    <VExpansionPanels multiple v-model="panel">
      <VExpansionPanel class="p-4">
        <VExpansionPanelTitle class="pb-5">
          <span>
            <p><b>#Order:</b> {{ appId }} </p>

            <div class="pl-5">
              <p><b> Appiontment Date:</b> July 04, 2024 02:00 AM </p>
            </div>
            <div class="pl-5">
              <p><b> Timezone:</b> Asia Karachi</p>
            </div>
            <div class="pl-5">
              <b>Product:</b> 2
            </div>
          </span>

        </VExpansionPanelTitle>

        <VExpansionPanelText>
          <VRow>
            <VDivider />
            <VCol cols="12" md="8">
              <VCard class="rounder-4">
                <div class="d-flex align-center justify-space-between gap-1 mb-6">
                  <div class="text-body-1 text-high-emphasis font-weight-medium">
                    <v-icon class="mr-2" color="rgb(var(--v-theme-yellow))">mdi-shopping-cart</v-icon>
                    Order Details
                  </div>
                </div>
                <v-data-table :headers="dessertHeaders" :items="desserts">
                </v-data-table>
              </VCard>
            </VCol>

            <VCol cols="12" md="4">
              <VCard class="mb-6" border>
                <VCardText>
                  <div class="d-flex align-center justify-space-between gap-1 mb-6">
                    <div class="text-body-1 text-high-emphasis font-weight-medium">
                      <v-icon class="mr-2" color="rgb(var(--v-theme-yellow))">mdi-calendar-clock</v-icon>
                      Appointment Details
                    </div>
                  </div>
                  <div class="appointment-details">
                    <div class="detail-item">
                      <span class="detail-label">Appointment At:</span>
                      <span class="detail-value">July 04, 2024 02:00 AM</span>
                    </div>
                  </div>
                  <div class="appointment-details">
                    <div class="detail-item pt-1">
                      <span class="detail-label">Timezone:</span>
                      <span class="detail-value pl-4">Asia/Karachi</span>
                    </div>
                  </div>
                </VCardText>
              </VCard>
            </VCol>
          </VRow>
        </VExpansionPanelText>
      </VExpansionPanel>
    </VExpansionPanels>


    <!-- <VCardText class="d-flex flex-column gap-y-4 p-0 rounded-3"> -->
    <VCard v-if="scheduleDate && scheduleTime && callEnd == null" border class="rounded-3" flat>
      <VCardText class="d-flex flex-sm-row flex-column pa-5 py-2">
        <div class="text-no-wrap text-base m-0 pr-9 mr-9" color="secondary">
          <!-- <VImg
                  :src="card.image"
                  :width="60"
                  :height="25"
                />  -->
          <p class="text-secondary mb-2 my-0">DateTime</p>
          <p class="text-base text-bold">
            <b>{{ scheduleDate }} {{ scheduleTime }}</b>

          </p>
          <!-- <span class="text-body-1">**** **** **** {{ card.number.substring(card.number.length - 4) }}</span> -->
        </div>
        <div class="text-no-wrap text-base m-0" color="secondary">
          <!-- <VImg
                  :src="card.image"
                  :width="60"
                  :height="25"
                />  -->
          <p class="text-secondary mb-2 my-0">Timezone</p>
          <p class="text-base">
            <b>{{ timeZone }} </b>

          </p>
        </div>

        <VSpacer />

        <div class="d-flex flex-column text-sm-end gap-2">
          <div class="order-sm-0 order-1 pt-0 mt-3">
            <RouterLink v-if="isMeetingEnable" to="/queue" target="_blank">
              <VBtn color="primary" class="me-2">
                Go to Meeting
              </VBtn>
            </RouterLink>
            <span v-else>
              <VBtn class="" color="primary" disabled>Go to Meeting
              </VBtn>
            </span>
          </div>

          <!-- <span class="mt-auto order-sm-1 order-0">Card expires at {{ card.expiry }}</span> -->
        </div>
      </VCardText>
    </VCard>
    <VCard border flat v-else>

      <VAlert border="start" color="rgb(var(--v-theme-yellow))" variant="tonal">
        <div class="text-center">No data found</div>
      </VAlert>

    </VCard>

    <!-- </VCardText> -->

  </VCol>


</template>
<style scoped>
.v-card-title {
  font-weight: 700 !important;
}

.v-table {
  border-radius: 10px !important;
  line-height: 4.5;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff !important;
}

.v-table__wrapper {
  background-color: #fff !important;
}

th.v-data-table__td.v-data-table-column--align-start.v-data-table__th {
  background-color: #fff !important;
  font-weight: 800px;
}

th.v-data-table__td.v-data-table-column--align-start.v-data-table__th {
  background-color: #fff !important;
  font-weight: 800px !important;
}

.v-data-table-header__content>span {
  font-weight: 700 !important;
}

button.v-btn.v-btn--icon.v-theme--light.text-primary.v-btn--density-default.v-btn--size-small.v-btn--variant-text {
  font-size: 16px;
}

.v-data-table-header__content {
  font-weight: 700 !important;
  background-color: white !important;
}

.v-table.v-table--has-top.v-table--has-bottom.v-theme--light.v-table--density-default.v-data-table {
  border-radius: 10px !important;
}
</style>
