<script setup>
import axios from '@axios';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const doctorAppiontments = ref([]);
const isButtonVisible = ref(true);
const isLoadingVisible = ref(true);
const alertMessage = ref(false);
const isdialogOpen = ref(false);
const isAccess = ref(localStorage.getItem('user_role'));
const isAgent = ref(localStorage.getItem('user_role'));
const comingUser = ref(null);

const callEndMesage = ref(null);
onMounted(() => {

  comingUser.value = localStorage.getItem('cominguser');
  callEndMesage.value = localStorage.getItem('call-end-message');
  const access_token = localStorage.getItem('access_token');
  const userRole = localStorage.getItem('user_role') || '';
  if (userRole == 'patient') {
    const patient_id = localStorage.getItem('patient_id');
    axios.get('api/doctor-appointments/' + patient_id, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${access_token}`
      }
    })
      .then(response => {
        doctorAppiontments.value = response.data;
        isButtonVisible.value = true;
        isLoadingVisible.value = false;
        localStorage.removeItem('call-end-message');
        localStorage.removeItem('cominguser');
      })
      .catch(error => {
        console.error(error);
        doctorAppiontments.value = [];
      });
  } else {
    axios.post('/agent/api/get-doctors-appointment-list')
      .then(response => {
        doctorAppiontments.value = response.data;
        isButtonVisible.value = false;
        isLoadingVisible.value = false;
      })
      .catch(error => {
        console.error(error);
        doctorAppiontments.value = [];
      });
  }

})
const openDialog = (item) => {
  localStorage.setItem('appiontment-id', item.appointment_id);
  let role = localStorage.getItem('user_role');
  if (role == 'patient')
    router.push('/appiontments-detail');
  else
    router.push('/provider/appiontments-detail');
};

const search = ref('');
const headers = [
  { align: 'start', key: 'patient_name', sortable: false, title: 'Patient Name' },
  { key: 'appointment_time', title: 'Appionment Date' },
  { key: 'appointment_id', title: 'Action' },

];

const formattedAppointments = computed(() => {
  return doctorAppiontments.value.map(appointment => ({
    ...appointment,
    patient_name: getFullName(appointment.first_name, appointment.last_name),
  }));
});

function getFullName(firstName, lastName) {
  // 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 firstName + ' ' + lastName; // For now, just return the first name
}

const filteredDesserts = computed(() => {
  // Perform filtering based on the search term
  return doctorAppiontments.value.filter(dessert =>
    dessert.name.toLowerCase().includes(search.value.toLowerCase())
  );
});
const goToQueue = () => {
  router.replace(route.query.to && route.query.to != '/doctor-appiontments' ? String(route.query.to) : '/queue')
};
</script>
<template>

  <v-card flat>
    <v-card-title class="d-flex align-center pe-2">
      <v-btn v-if="isAccess == 'patient'" @click="goToQueue()" class="text-capitalize text-white">
        <!-- <router-link to="/queue" > -->
        Connect Live Chat
        <!-- </router-link> -->
      </v-btn>
      <v-spacer></v-spacer>
      <v-spacer></v-spacer>
      <v-spacer></v-spacer>
      <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-card-title>

    <v-data-table :headers="headers" :items="formattedAppointments" :search="search">
      <template #item.appointment_id="{ item }">
        <VBtn class="text-capitalize text-white" @click="openDialog(item)"> Detail</VBtn>
      </template>
    </v-data-table>

  </v-card>
</template>
