<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useStore } from 'vuex';
import { ADMIN_AUTH_CALENDLY_API, ADMIN_AUTH_CALENDLY_EVENTS_API, ADMIN_AUTH_CALENDLY_RESET_EVENTS_API, ADMIN_AUTH_CALENDLY_SET_EVENTS_API } from '../../../constants.js';

const store = useStore();
const errors = ref({ name: undefined });
const accountData = { name: '' };
const refVForm = ref();
const isConfirmDialogOpen = ref(false);
const accountDataLocal = ref(structuredClone(accountData));
const getIsTonalSnackbarVisible = ref(false);
const events = ref([]);
const selectedEventIndex = ref(null);
onMounted(async () => {
  await getEvents();
});
// Fetch events after form submission
const onSubmit = async () => {
  const { valid } = await refVForm.value.validate();
  console.log(valid);
  if (valid) {
    try {
      await store.dispatch('updateIsLoading', true);

      // First API call for authorization
      const response = await axios.post(ADMIN_AUTH_CALENDLY_API);
      const authUrl = response.data.url; // Assuming the URL is returned in the response as `url`

      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateSuccessMsg', true);
      store.dispatch('updateIsTonalSnackbarMsg', 'Connection Request Sent!');
      
      // Open the auth URL in a new tab
      if (authUrl) {
        window.open(authUrl, '_blank'); // Open the URL in a new tab
      }

      await getEvents();
    } catch (error) {
      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateErrorMessage', error);
      console.error("Error fetching events:", error);
    }
  }
};
const onReset = async () => {
  const { valid } = await refVForm.value.validate();
  console.log(valid);
  if (valid) {
    try {
      await store.dispatch('updateIsLoading', true);

      // First API call for authorization
      const response = await axios.post(ADMIN_AUTH_CALENDLY_RESET_EVENTS_API);
      const authUrl = response.data.url; // Assuming the URL is returned in the response as `url`

      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateSuccessMsg', true);
      store.dispatch('updateIsTonalSnackbarMsg', 'Event URI reset!');
    } catch (error) {
      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateErrorMessage', error);
      console.error("Error fetching events:", error);
    }
  }
};
const getEvents = async() => {
  events.value = []
  // Fetch events after successful authorization
  const respEv = await axios.post(ADMIN_AUTH_CALENDLY_EVENTS_API);
  console.log('Events Response: ', respEv.data);

  // Check if the API returned events and update the reactive events array
  if (respEv.data.events && Array.isArray(respEv.data.events)) {
    events.value.push(...respEv.data.events); // Assign events to the ref
  } else {
    console.warn("No events found in the response.");
  }
  console.log('events.value',events.value)
};
const eventClick = async (url,index) => {
  console.log('url',url)
  if(selectedEventIndex.value != index){
    await store.dispatch('updateIsLoading', true);
    try {
      // Define your payload data
      const payload = {
        // Add any necessary data here
        url: url,
        // You can add more key-value pairs as needed
      };

      // Make the POST request with the URL and payload
      const response = await axios.post(ADMIN_AUTH_CALENDLY_SET_EVENTS_API, payload);
      
      // Log the response from the server
      console.log('Response:', response.data);
      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateSuccessMsg', true);
      store.dispatch('updateIsTonalSnackbarMsg', response.data.message);
      selectedEventIndex.value = index;
      
      // Handle the response as needed (e.g., updating state, showing notifications, etc.)
    } catch (error) {
      await store.dispatch('updateIsLoading', false);
      store.dispatch('updateErrorMessage', error);
      console.error('Error making POST request:', error);
    }
  }
};
</script>



<template>

  <VRow>
  
    <VCol cols="12">
      <VCard>
        <VCardText>
          <!-- 👉 Form -->
          <VForm ref="refVForm">
            <VRow>
                <VCol
                    cols="12"
                    class="d-flex flex-wrap gap-4"
                >
                    <p>To connect the calendly you have to click on "Connect" button then it will authorize to get the timeslots.</p>
                </VCol>
                <VCol
                    cols="2"
                    class="d-flex flex-wrap gap-4"
                >
                    <VBtn  @click.prevent="onSubmit" block>Connect</VBtn>
                </VCol>
                <VCol
                    cols="2"
                    class="d-flex flex-wrap gap-4"
                >
                    <VBtn  @click.prevent="onReset" block>Reset</VBtn>
                </VCol>
                <VCol
                    cols="12"
                    class="d-flex flex-wrap gap-4"
                >
                  <v-list>
                    <v-list-item v-for="(event, index) in events"
                      :key="index"
                      :class="{'selected': selectedEventIndex === index}" style="border:1px solid silver;border-radius: 5px;cursor: pointer;">
                      <v-list-item-content @click="eventClick(event.uri,index)">
                        <v-list-item-title>{{ event.slug }}</v-list-item-title>
                        <v-list-item-subtitle>{{ event.type }}</v-list-item-subtitle>
                      </v-list-item-content>
                    </v-list-item>
                  </v-list>
                </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </VCol>

  </VRow>

  <!-- Confirm Dialog -->
  <ConfirmDialog
    v-model:isDialogVisible="isConfirmDialogOpen"
    confirmation-question="Are you sure you want to deactivate your account?"
    confirm-title="Deactivated!"
    confirm-msg="Your account has been deactivated successfully."
    cancel-title="Cancelled"
    cancel-msg="Account Deactivation Cancelled!"
  />
</template>
<style>
.selected {
  border: 2px solid green !important; /* Change border to green when selected */
}
</style>
