<script setup>
import axios from '@axios';
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const queueUsers = ref([]);
const router = useRouter()
const route = useRoute()
const isLoadingVisible = ref(false);
const usertime = ref(null);
const agentId = ref(localStorage.getItem('agent_id'))
const recordVid = ref(true)
const enableAi = ref(true)
const currentQueue = computed(() => {
  return queueUsers.value.findIndex(user => user.id == localStorage.getItem('userData'))
});

const registrationTimeAgo = () => {
  const currentDate = new Date();
  const registrationDate = new Date(usertime.value * 1000);

  const timeDifference = currentDate - registrationDate;
  const seconds = Math.floor(timeDifference / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  if (seconds < 60) {
    return `${seconds} second${seconds !== 1 ? 's' : ''} ago`;
  } else if (minutes < 60) {
    return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
  } else if (hours < 24) {
    return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
  } else if (days < 7) {
    return `${days} day${days !== 1 ? 's' : ''} ago`;
  }
}
const count = ref();
const states = ref([
  { name: 'Howland Island', abbreviation: 'UM-84' },
  { name: 'Delaware', abbreviation: 'DE' },
  { name: 'Maryland', abbreviation: 'MD' },
  { name: 'Baker Island', abbreviation: 'UM-81' },
  { name: 'Kingman Reef', abbreviation: 'UM-89' },
  { name: 'New Hampshire', abbreviation: 'NH' },
  { name: 'Wake Island', abbreviation: 'UM-79' },
  { name: 'Kansas', abbreviation: 'KS' },
  { name: 'Texas', abbreviation: 'TX' },
  { name: 'Nebraska', abbreviation: 'NE' },
  { name: 'Vermont', abbreviation: 'VT' },
  { name: 'Jarvis Island', abbreviation: 'UM-86' },
  { name: 'Hawaii', abbreviation: 'HI' },
  { name: 'Guam', abbreviation: 'GU' },
  { name: 'United States Virgin Islands', abbreviation: 'VI' },
  { name: 'Utah', abbreviation: 'UT' },
  { name: 'Oregon', abbreviation: 'OR' },
  { name: 'California', abbreviation: 'CA' },
  { name: 'New Jersey', abbreviation: 'NJ' },
  { name: 'North Dakota', abbreviation: 'ND' },
  { name: 'Kentucky', abbreviation: 'KY' },
  { name: 'Minnesota', abbreviation: 'MN' },
  { name: 'Oklahoma', abbreviation: 'OK' },
  { name: 'Pennsylvania', abbreviation: 'PA' },
  { name: 'New Mexico', abbreviation: 'NM' },
  { name: 'American Samoa', abbreviation: 'AS' },
  { name: 'Illinois', abbreviation: 'IL' },
  { name: 'Michigan', abbreviation: 'MI' },
  { name: 'Virginia', abbreviation: 'VA' },
  { name: 'Johnston Atoll', abbreviation: 'UM-67' },
  { name: 'West Virginia', abbreviation: 'WV' },
  { name: 'Mississippi', abbreviation: 'MS' },
  { name: 'Northern Mariana Islands', abbreviation: 'MP' },
  { name: 'United States Minor Outlying Islands', abbreviation: 'UM' },
  { name: 'Massachusetts', abbreviation: 'MA' },
  { name: 'Connecticut', abbreviation: 'CT' },
  { name: 'Florida', abbreviation: 'FL' },
  { name: 'District of Columbia', abbreviation: 'DC' },
  { name: 'Midway Atoll', abbreviation: 'UM-71' },
  { name: 'Navassa Island', abbreviation: 'UM-76' },
  { name: 'Indiana', abbreviation: 'IN' },
  { name: 'Wisconsin', abbreviation: 'WI' },
  { name: 'Wyoming', abbreviation: 'WY' },
  { name: 'South Carolina', abbreviation: 'SC' },
  { name: 'Arkansas', abbreviation: 'AR' },
  { name: 'South Dakota', abbreviation: 'SD' },
  { name: 'Montana', abbreviation: 'MT' },
  { name: 'North Carolina', abbreviation: 'NC' },
  { name: 'Palmyra Atoll', abbreviation: 'UM-95' },
  { name: 'Puerto Rico', abbreviation: 'PR' },
  { name: 'Colorado', abbreviation: 'CO' },
  { name: 'Missouri', abbreviation: 'MO' },
  { name: 'New York', abbreviation: 'NY' },
  { name: 'Maine', abbreviation: 'ME' },
  { name: 'Tennessee', abbreviation: 'TN' },
  { name: 'Georgia', abbreviation: 'GA' },
  { name: 'Louisiana', abbreviation: 'LA' },
  { name: 'Nevada', abbreviation: 'NV' },
  { name: 'Iowa', abbreviation: 'IA' },
  { name: 'Idaho', abbreviation: 'ID' },
  { name: 'Rhode Island', abbreviation: 'RI' },
  { name: 'Washington', abbreviation: 'WA' },
  { name: 'Ohio', abbreviation: 'OH' },
  // ... (add the rest of the states)
]);


const selectedStateName = (stateName) => {
  console.log('queueUsers', stateName);
  const selectedState = states.value.find(s => s.abbreviation === stateName);

  return selectedState ? selectedState.name : '';
};


onMounted(async () => {
  isLoadingVisible.value = true;
  window.Pusher = Pusher;
  const key = 'bc8bffbbbc49cfa39818';
  const cluster = 'mt1';
  let echo = new Echo({
    broadcaster: 'pusher',
    key: key,
    cluster: cluster,
    forceTLS: true,
    auth: {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('access_token'),
      },
    },
  });
  //presence channel ((user bio show))

  echo.join(`dhkjkiplqe84sdaqf17nqg`)
    .here((users) => {  //existing user/ including current user
      users.forEach((user, index) => {
        usertime.value = user.time;
        user.waitingTime = registrationTimeAgo();
        user.state = selectedStateName(user.state);
      });
      queueUsers.value = users.filter(user => user.type == "patient");
      console.log("alluser", users);
    })
    .joining((user) => {
      //new user
      console.log('joining', user);
      if (user.type != "patient")
        return
      usertime.value = user.time;
      user.waitingTime = registrationTimeAgo();
      user.state = selectedStateName(user.state);
      queueUsers.value.push(user);
    })
    .leaving((user) => {
      console.log('leaving', user.name);
      queueUsers.value = queueUsers.value.filter(u => u.id !== user.id);
      console.log("CurrentUser", queueUsers);
      if (user.type != "patient")
        return
    })
    .error((error) => {
      console.error(error);
    });
  isLoadingVisible.value = false;

  await axios.post('/agent/api/patient-recording-switch-get/' + agentId.value)
    .then(response => {
      console.log('rec ', response.data.recording_switch)
      if (response.data.recording_switch == 1)
        recordVid.value = true
      else
        recordVid.value = false
    })
    .catch(error => {
      console.error('error recording ', error.response.data);
    });

  await axios.post('/agent/api/patient-ai-transcript-switch-get/' + agentId.value)
    .then(response => {
      console.log('enable ai ', response.data.ai_switch)
      if (response.data.ai_switch == 1)
        enableAi.value = true
      else
        enableAi.value = false
    })
    .catch(error => {
      console.error('error enableAi ', error.response.data);
    });


});


const recordVideo = async () => {

  if (recordVid.value == true) {
    await axios.post('/agent/api/patient-recording-switch/' + agentId.value + '/1',)
      .catch(error => {
        console.error('error recording ', error.response.data);
      });
  } else {
    await axios.post('/agent/api/patient-recording-switch/' + agentId.value + '/0',)
      .catch(error => {
        console.error('error recording ', error.response.data);
      });
  }


}

const enableAiFun = async () => {

  if (enableAi.value == true) {
    await axios.post('/agent/api/patient-ai-transcript-switch/' + agentId.value + '/1',)
      .catch(error => {
        console.error('error recording ', error.response.data);
      });
  } else {
    await axios.post('/agent/api/patient-ai-transcript-switch/' + agentId.value + '/0',)
      .catch(error => {
        console.error('error recording ', error.response.data);
      });
  }


}

const joinCall = async (patient_id, appiontment_id) => {
  console.log('Join call');
  localStorage.setItem('patient_id', patient_id);
  isLoadingVisible.value = true;
  const agent_id = localStorage.getItem('agent_id');

  const access_token = localStorage.getItem('access_token');
  // const patient_appiontment_id = localStorage.getItem('patient_appiontment_id');
  console.log(access_token);
  await axios.post('/agent/api/start-call/' + patient_id + '/' + agent_id + '/' + appiontment_id, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${access_token}`
    }
  })
    .then(response => {
      console.log("Start Call", response.data);
      localStorage.setItem('agent_meeting_id', response.data.meeting_id);
      localStorage.setItem('patient_appiontment_id', response.data.appointment_id);
      console.log('Aegnt_meetingId', response.data.meeting_id);
      router.push('/conference');
    })
    .catch(error => {
      console.error(error.response.data);
      isLoadingVisible.value = false;
    });


}

</script>
<template>
  <VDialog v-model="isLoadingVisible" 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>
  <VRow>
    <VCol cols="12">
      <v-switch v-model="enableAi" @change="enableAiFun" label="Enable AI?"
        style="float:right;margin-right: 20px;"></v-switch>
      <v-switch v-model="recordVid" @change="recordVideo" label="Record Video?"
        style="float:right;margin-right: 20px;"></v-switch>
    </VCol>
  </VRow>
  <VList density="compact">
    <div class="px-4 border text-center" v-if="queueUsers.length === 0">
      <span class="text-center">
        <p class="mt-3 fs-0">No data available</p>
      </span>
    </div>
    <div class="px-4" v-else v-for="(user, index) of queueUsers" :key="index">
      <VListItem :value="user.id" border class="py-3" @click="joinCall(user.id, user.appointments.id)">
        <template #prepend>
          <VListItemAction start>
            <!-- Your prepend content -->
          </VListItemAction>
        </template>

        <VListItemTitle>{{ user.name }}</VListItemTitle>
        <VListItemSubtitle class="py-1 user-item" style="">
          <span v-if="user.address">{{ user.address }}, </span>
          <span v-if="user.city">{{ user.city }}, </span>
          <span v-if="user.state">{{ user.state }} &nbsp;</span>
          <span v-if="user.zip_code">{{ user.zip_code }}, </span>
          <span v-if="user.country">{{ user.country }}</span>
        </VListItemSubtitle>
        <VListItemSubtitle>{{ user.waitingTime }}</VListItemSubtitle>
      </VListItem>
    </div>
  </VList>
</template>
<style>
@media (min-width: 320px) and (max-width: 768px) {
  .user-item {
    min-height: 60px;
  }
}
</style>
<style scoped>
.green-button {
  background-color: #16ba16e8;
  color: white !important;
  /* Optionally set text color */
}

.red-button {
  background-color: #ff0000;
  color: white !important;
  /* Optionally set text color */
}
</style>
