<script setup>
import axios from '@axios';
// import { VideoPlayer } from '@videojs-player/vue';
import phpUnserialize from 'phpunserialize';
// import 'video.js/dist/video-js.css';
const appiontmentDetail = ref();
const appionmentDate = ref();
const patientAddress = ref();
const patientDOb = ref();
const patientName = ref();
const patientID = ref();
const labAddress = ref();
const labName = ref();
const labDistance = ref();
const labContact = ref();
const labBookDate = ref();
const labBookTime = ref();
const video_url = ref();
const selectedLab = ref();
const labDetail = ref();
const questionAnswer = ref([]);
const appiontmentDate = ref();
const agent_appointment = ref([]);
const questions = ref([]);
const answers = ref([]);
onMounted(async () => {
  const access_token = localStorage.getItem('access_token');
  const appiontment_id = localStorage.getItem('appiontment-id');
  await axios.post('/agent/api/appointment-detail/' + appiontment_id, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${access_token}`
    }
  })
    .then(response => {
      console.log(response.data);
      video_url.value = response.data.video_url;
      appiontmentDetail.value = response.data;
      agent_appointment.value = response.data.agent_appointment;
      let patientData = response.data.patient
      appionmentDate.value = appiontmentDetail.value.agent_appointment.appointment_time ? appiontmentDetail.value.agent_appointment.appointment_time : '';
      patientName.value = agent_appointment.value.patient_name ? agent_appointment.value.patient_name : '';
      patientDOb.value = appiontmentDetail.value.patient.dob ? '(' + appiontmentDetail.value.patient.age + 'yrs old)' : ' ';

      patientAddress.value = (patientData.address ? patientData.address + ', ' : '') +
        (patientData.city ? patientData.city + ', ' : '') +
        (patientData.state ? patientData.state + ' ' : '') +
        (patientData.zip_code ? patientData.zip_code + ', ' : '') +
        (patientData.country ? patientData.country : '');

      // Remove trailing comma and space if present
      patientAddress.value = patientAddress.value.replace(/,\s*$/, '');

      patientID.value = patientData.id
      console.log('patientData.id', patientID.value)
    })

    .catch(error => {
      console.error(error);
      appiontmentDetail.value = [];
      patientAddress.value = '';
    });

  await axios.post('agent/api/questions-answers/' + patientID.value + '/' + appiontment_id)
    .then(r => {
      console.log("Question", r.data);
      questions.value = r.data;
    }).catch(error => {
      console.log("ErrorResponse", error);
      isLoadingVisible.value = false;
    });

});
const groupedQuestions = computed(() => {
  const groups = {};
  for (const key in questions.value) {
    if (questions.value.hasOwnProperty(key)) {
      let groupQuestions = questions.value[key];
      groupQuestions.forEach(question => {
        const groupId = question.group_id;
        answers.value[question.id] = question.answer
        if (!groups[groupId]) {
          groups[groupId] = {
            name: key,
            questions: [],
          };
        }

        groups[groupId].questions.push(question);
      });
    }
  }




  console.log("groups", groups);
  // Convert groups object to an array
  return Object.values(groups);
});

const parseOptions = (optionsString) => {
  try {
    const optionsArray = phpUnserialize(optionsString);
    return optionsArray.map((option, index) => ({ key: index, value: option }));
  } catch (error) {
    console.error('Error parsing options:', error);
    return [];
  }
};

</script>
<template>
  <v-row>
    <!-- First Column -->
    <v-col cols="12" md="8">
      <video-player :src="video_url" controls :loop="true" :volume="0.6" responsive="true" width="820" height="400"
        aspectRatio="16:9" />
    </v-col>

    <!-- Second Column -->
    <v-col cols="12" md="4">

      <v-list style="height:auto">
        <v-list-item-group>
          <v-list-item v-if="patientName || patientDOb">
            <v-list-item-content class="lab_address">
              <v-list-item-subtitle>
                <b>Patient:</b>
              </v-list-item-subtitle>
              <v-list-item-subtitle>
                {{ patientName }} {{ patientDOb }}
              </v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>
          <v-list-item v-if="appionmentDate">
            <v-list-item-content class="lab_address">
              <v-list-item-subtitle>
                <b>Appiontment Date:</b>
              </v-list-item-subtitle>
              <v-list-item-subtitle>
                {{ appionmentDate }}
              </v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>
        </v-list-item-group>
      </v-list>
      <v-list-item v-if="patientAddress">
        <v-list-item-subtitle><b>Address</b></v-list-item-subtitle>
        <v-list-item-title class="text-wrap" style="font-size: 13px;color:#939393">
          {{ patientAddress }}
        </v-list-item-title>
      </v-list-item>


    </v-col>
  </v-row>
  <VRow>
    <VCol cols="12" md="12">
      <VExpansionPanels variant="accordion" class="expansion-panels-width-border">
        <VExpansionPanel v-for="(group, groupIndex) in groupedQuestions" :key="groupIndex" :open="group.isOpen">
          <VExpansionPanelTitle>
            <b>{{ group.name }}</b>
          </VExpansionPanelTitle>
          <VExpansionPanelText>
            <VExpansionPanels>
              <VExpansionPanel v-for="(question, questionIndex) in group.questions" :key="questionIndex"
                :open="question.isOpen">
                <VExpansionPanelTitle>
                  {{ question.id }}. {{ question.question }} ?
                </VExpansionPanelTitle>
                <VExpansionPanelText>
                  <!-- Conditionally render input components based on question type -->
                  <template v-if="question.type === 'text'">
                    <VTextField :type="question.type" :id="'question_' + question.id" size="500"
                      v-model="answers[question.id]" />
                  </template>
                  <template v-else-if="question.type === 'radio'">
                    <VRadioGroup v-model="answers[question.id]">
                      <VRadio v-for="(option, optionIndex) in parseOptions(question.options)" :key="optionIndex"
                        :label="option.value" :value="option.value" />
                    </VRadioGroup>
                  </template>
                  <template v-else-if="question.type === 'textarea'">
                    <VTextarea :type="question.type" :id="'question_' + question.id" v-model="answers[question.id]" />
                  </template>
                  <template v-else-if="question.type === 'checkbox'">
                    <VCheckboxGroup v-model="answers[question.id]">
                      <VCheckbox :type="question.type" v-for="(option, optionIndex) in question.options"
                        :key="optionIndex" :label="option" :value="option" />
                    </VCheckboxGroup>
                  </template>
                  <!-- Add more conditions for other types if needed -->
                </VExpansionPanelText>
              </VExpansionPanel>
            </VExpansionPanels>
          </VExpansionPanelText>
        </VExpansionPanel>
      </VExpansionPanels>
    </VCol>
  </VRow>
</template>
<style>
.lab_address div {

  margin-top: 5px;
  margin-bottom: 5px;
}

button.v-expansion-panel-title {
  background-color: rgb(var(--v-theme-yellow)) !important;
  color: #fff;
}

button.v-expansion-panel-title.bg-secondary {
  background-color: rgb(var(--v-theme-yellow)) !important;
  color: #fff;
}

button.v-expansion-panel-title {
  background-color: rgb(var(--v-theme-yellow)) !important;
  color: #fff;
}

button.v-expansion-panel-title.v-expansion-panel-title--active {
  background-color: rgb(var(--v-theme-yellow)) !important;
  color: #fff;
}

span.v-expansion-panel-title__icon {
  color: #fff
}
</style>
