<script setup>
import axios from '@axios';
import avatar1 from '@images/avatars/avatar-1.png';
const profileDetail = ref();
const profileName = ref();
const success = ref();
const currentDialoagkey = ref('')
const email = ref();
const fullAddress = ref();
const phone = ref();
const dob = ref();
const gender = ref();
const marital_status = ref();
const isDialogVisible = ref(false)
const height = ref();
const weight = ref();
const planName = ref();
const planAmount = ref();
const finalArray = ref([]);
const answers = ref([]);
const questionAnswer = ref([]);
const isLoadingVisible = ref(false);
const isLoadingMedicalHistoryVisible = ref(true);

onMounted(async () => {

    isLoadingVisible.value = true;
    await getPatientInfo();
    await getPlanInfo();
    await getPatientMedicalHistory();
    finalArray.value = getFinalArray(questions.value, questionAnswer.value);
    console.log("finalArray", finalArray);
    isLoadingVisible.value = false;
});

const getFinalArray = (questions, answers) => {
    const finalArray = [];

    questions.forEach(question => {
        const answer = answers.find(answer => answer.question_key === question.question_key);
        if (answer) {
            finalArray.push({
                ...question,
                answer: answer.answer
            });
        } else {
            finalArray.push({
                ...question,
                answer: "Not Answer"
            });
        }
    });

    return finalArray;
};

const getPatientInfo = async () => {
    const patient_id = localStorage.getItem('patient_id')
    const access_token = localStorage.getItem('access_token');
    await axios.post('/api/get-patient-detail/' + patient_id, {
        headers: {
            'Authorization': `Bearer ${access_token}`,
        }
    })
        .then(response => {
            console.log('Response:', response.data);
            if (response.data) {
                let patientData = response.data.patient
                profileName.value = patientData.first_name + ' ' + patientData.last_name
                email.value = patientData.email
                phone.value = patientData.phone_no
                dob.value = patientData.dob
                gender.value = patientData.gender
                height.value = patientData.height
                weight.value = patientData.weight
                marital_status.value = patientData.marital_status
                fullAddress.value = patientData.city + ' ' + patientData.state + ' ' + patientData.country

            } else {
                isLoadingVisible.value = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

const getPlanInfo = async () => {

    const patient_id = localStorage.getItem('patient_id')
    const access_token = localStorage.getItem('access_token');
    isLoadingVisible.value = true;
    await axios.post('/api/get-plan-by-patient/' + patient_id, {
        headers: {
            'Authorization': `Bearer ${access_token}`,
        }
    })
        .then(response => {
            console.log('Response:', response.data);
            if (response.data) {
                let planData = response.data
                console.log('plan ', planData)
                planName.value = planData.plan_name
                planAmount.value = planData.plan_amount

            } else {
                isLoadingVisible.value = false;
            }
        })
        .catch(error => {
            isLoadingVisible.value = false;
            console.log('Error:', error);
        });
}

const getPatientMedicalHistory = async () => {
    isLoadingMedicalHistoryVisible.value = true;
    const patient_id = localStorage.getItem('patient_id');
    const access_token = localStorage.getItem('access_token');
    await axios.post('api/medical-history-question-get/' + patient_id, {
        headers: {
            'Authorization': `Bearer ${access_token}`,
        }
    })
        .then(response => {
            console.log('Response:', response.data);
            if (response.data) {

                questionAnswer.value = response.data.answers;
                console.log("ResponseAnswer", questionAnswer.value);
                isLoadingMedicalHistoryVisible.value = false;
            } else {
                isLoadingVisible.value = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            questionAnswer.value = [];
        });
}

// const groupedQuestions = computed(() => {
//     const groups = {};
//     console.log("QuestionValue", questions.value);
//     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);
//     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 [];
//     }
// };

const questions = ref([
    {
        question_key: 'why_interested_hrt',
        question: "What aspects of hormone replacement therapy (HRT) intrigue you?",
        type: "text",
    },
    {
        question_key: 'goal_loss_weight',
        question: "Is your objective with the program to achieve weight loss?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'what_biological_sex',
        question: "What is your assigned sex at birth?",
        type: "radio",
        options: ["Male", "Female"],
    },
    {
        question_key: '3_years_physical_test',
        question: "Have you undergone a comprehensive physical examination by a medical professional within the past three years, which included assessments of vital signs such as weight, blood pressure, and heart rate?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'medical_problems',
        question: "Did you experience any medical issues? If so, could you please elaborate?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'have_prostate_cancer',
        question: "Have you ever received a diagnosis of prostate cancer?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'what_height',
        question: "How tall are you?",
        type: "dropdown",
        options: ["5 ft 1 in",
            "5 ft 2 in",
            "5 ft 3 in",
            "5 ft 4 in",
            "5 ft 5 in",
            "5 ft 6 in",
            "5 ft 7 in",
            "5 ft 8 in",
        ],
    },
    {
        question_key: 'whight',
        question: "What is your weight?",
        type: "text",
    },
    // {
    //     question_key: 'birthdate',
    //     question: "When were you born?",
    //     type: "date",
    //     sub_title: 'To proceed with medication, kindly input your accurate date of birth using the format mm/dd/yyyy.'
    // },
    {
        question_key: 'past_harmone_treatments',
        question: "Have you been prescribed any hormone treatments currently or in the past?",
        type: "radio",
        options: ["thyroid_medication", "testosterone_treatment", "estrogen_blocker", "hgh", "ipamoreline", "colomipheine", "hcg", "other", "none"],
    },
    {
        question_key: 'take_medications',
        question: "Are you currently using or have you used any over-the-counter or prescription medications, excluding hormone treatments? (Please note that your responses will be cross-checked against prescription and insurance records. Failure to disclose current prescriptions and/or medical conditions may result in disapproval for your safety.)",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'have_medications_allegies',
        question: "Do you have any allergies to medications?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'plan_children',
        question: "Do you intend to have children at some point in the future?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'partner_pregnant',
        question: "Is your partner currently pregnant or breastfeeding?",
        type: "radio",
        options: ["Yes", "No", "not applicab_e"],
    },
    {
        question_key: 'experience_ed',
        question: "Are you currently experiencing any erectile dysfunction (ED) issues?",
        type: "radio",
        options: ["never", "almost_never", "occasionally", "almost_always", "always"],
    },
    {
        question_key: 'thyroid_disorders',
        question: "Have you ever been diagnosed with thyroid disorders such as hypothyroidism (underactive thyroid), hyperthyroidism (overactive thyroid), Hashimoto's Disease, or Graves' Disease?",
        type: "radio",
        options: ["Yes", "No"],
    },
    {
        question_key: 'family_history',
        question: "Does your family have a history of any of the following disorders?",
        type: "radio",
        options: ["drug_alcohol", "cancer", "heart_disease", "thyroid_disease", "low_testosterone",
            "none"],
    },
    {
        question_key: 'patient_concent',
        question: "Please read and  accept",
        linktext: "Patient Content",
        type: "signalCheckbox",
    },
    {
        question_key: 'appointment_cancel',
        question: "Please read and  accept",
        linktext: "Appointment Cancel",
        type: "signalCheckbox",
    },
    {
        question_key: 'medicare_disclaimer',
        question: "Please read and  accept",
        linktext: "Medicare Disclaimer",
        type: "signalCheckbox",
    },
    {
        question_key: 'telehealth_concent',
        question: "Please read and  accept",
        linktext: "Telehealth Concent",
        type: "signalCheckbox",
    },
    {
        question_key: 'secondary_contact',
        question: "Please read and  accept",
        linktext: "Secondary Contact Disclosure(optional)",
        type: "signalCheckbox",
    },

]);

const getCurrentDate = () => {
    const today = new Date();
    const year = today.getFullYear();
    let month = today.getMonth() + 1;
    let day = today.getDate();

    // Format the date to match the input type="date" format
    month = month < 10 ? `0${month}` : month;
    day = day < 10 ? `0${day}` : day;

    return `${year}-${month}-${day}`;
};

const openDialog = (question_key) => {
    currentDialoagkey.value = question_key;
    isDialogVisible.value = true;
    window.addEventListener('click', closeDialogOnOutsideClick);
};
const closeDialogOnOutsideClick = (event) => {
    const dialogElement = refs.myDialog.$el;
    if (!dialogElement.contains(event.target)) {
        isDialogVisible.value = false;
        window.removeEventListener('click', closeDialogOnOutsideClick);
    }
};
const handleContinueClick = (currentDialoagkey) => {
    isDialogVisible.value = false; // Hide the dialog
    answers.value[currentDialoagkey] = true; // Update the answers object
};
const skill = ref(20)
</script>

<template>
    <VRow>
        <VCol cols="12" lg="4">
            <VCard class="mb-3">
                <VCardText class="d-flex">
                    <!-- 👉 Avatar -->
                    <VAvatar rounded size="100" class="me-6" :image="avatar1" />

                    <!-- 👉 Upload Photo -->
                    <form class="d-flex flex-column justify-center gap-4">
                        <div class="d-flex flex-wrap gap-0 pt-0">
                            <h4 class="text-decoration-underline">{{profileName}}</h4>
                        </div>
                        <div class="d-flex flex-wrap gap-5">
                            <h4 class=""></h4>
                        </div>
                    </form>
                </VCardText>
                <VCardText>
                    <router-link to="/category">
                        <p class="text-xs text-primary text-decoration-underline">
                        <h1 class="text-xs text-primary">Complete Your Profile</h1>
                        </p>
                    </router-link>

                    <!-- <router-link to="/update">
                                <VBtn size="small">
                                    <VIcon icon="tabler-edit" size="20" class="me-2" />Update
                                </VBtn>
                            </router-link> -->
                    <div class="demo-space-y mt-3">
                        <VProgressLinear v-model="skill" color="success" class="rounded" height="20">
                            <template #default="{ value }">
                                <strong>{{ Math.ceil(value) }}%</strong>
                            </template>
                        </VProgressLinear>
                    </div>
                </VCardText>
            </VCard>
            <VCard class="mb-0">
                <VCardText>
                    <p class="text-xs">
                        <b>ABOUT</b>
                    </p>

                    <VList class="card-list text-medium-emphasis">
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-account" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Full Name:</span>
                                <span>{{ profileName }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-email" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Email:</span>
                                <span>{{ email }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-calendar" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">DOB:</span>
                                <span>{{ dob }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-user" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Gender:</span>
                                <span>{{ gender }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-users" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Material Status:</span>
                                <span>{{ marital_status }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-arrow-autofit-height" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Height:</span>
                                <span>{{ height }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-weight" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">weight:</span>
                                <span>{{ weight }}</span>
                            </VListItemTitle>
                        </VListItem>

                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-map-marker" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class=" text-wrap">Address: </span>
                                <span>{{ fullAddress }}</span>
                            </VListItemTitle>
                        </VListItem>

                        <VDivider class="my-2" />
                    </VList>

                    <p class="text-xs mt-5">
                        <b>CONTACTS</b>
                    </p>

                    <VList class="card-list text-medium-emphasis">
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="mdi-phone" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Contact:</span>
                                <span>{{ phone }}</span>
                            </VListItemTitle>
                        </VListItem>
                        <VDivider class="my-2" />
                    </VList>


                    <p class="text-xs mt-5">
                        <b>OVERVIEW</b>
                    </p>

                    <VList class="card-list text-medium-emphasis">
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-shopping-cart" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Select Plan:</span>
                                <span> {{ planName }}</span>
                            </VListItemTitle>

                        </VListItem>
                        <VListItem>
                            <template #prepend>
                                <VIcon icon="tabler-currency-dollar" size="20" class="me-2" />
                            </template>
                            <VListItemTitle>
                                <span class="font-weight-medium me-1">Amount:</span>
                                <span> ${{ planAmount }}</span>
                            </VListItemTitle>

                        </VListItem>

                    </VList>


                </VCardText>
            </VCard>
        </VCol>
        <VCol cols="12" lg="8">
            <VCard class="mb-4 mt-0">
                <VCardText>
                    <VRow class="justify-space-between pb-2">
                        <Vcol col="auto">
                            <p class="text-xs">
                                <b>Medical History</b>
                            </p>
                        </Vcol>
                        <Vcol col="auto">
                            <router-link to="/update">
                                <VBtn size="small">
                                    <VIcon icon="tabler-edit" size="20" class="me-2" />Update
                                </VBtn>
                            </router-link>

                        </Vcol>
                    </VRow>



                    <div class="spinner-container align-center" v-if="isLoadingMedicalHistoryVisible">
                        <v-progress-circular indeterminate color="primary"></v-progress-circular>
                    </div>
                    <!-- <VDialog v-model="isLoadingMedicalHistoryVisible" 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> -->


                    <div class="px-4 py-4">
                        <v-row v-for="(q, index) in  finalArray  " :key="index">
                            <v-col cols="12" md="12">
                                <template v-if="q.type === 'text'">
                                    <p><b class="justify-content">{{ q.question }}</b></p>
                                    <span v-if="q.answer == 'Not Answer'"><b>Answer:</b>
                                        <span class="text-danger">{{ q.answer }}</span></span>
                                    <span v-else><b>Answer:</b> {{ q.answer }}</span>
                                    <!-- <v-text-field class="col-md-4" v-model="q.answer" readonly /> -->
                                </template>
                                <template v-if="q.type === 'date'">
                                    <p><b>{{ q.question }}</b></p>
                                    <span><b>Answer:</b> {{ q.answer }}</span>
                                    <!-- <v-text-field class="col-md-4" :max="getCurrentDate()" :type="q.type"
                                        v-model="q.answer" readonly /> -->
                                </template>
                                <!-- <template v-if="q.type === 'signalCheckbox'">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" v-model="q.answer" disabled
                                            @click="openDialog(q.question_key)">
                                        <label class="form-check-label" for="flexCheckDisabled">
                                            {{ q.question }} <b class="text-reset" style="cursor: pointer;"
                                                @click="openDialog(q.question_key)">{{
                                    q.linktext }}</b>
                                        </label>
                                    </div>

                                </template> -->
                                <template v-else-if="q.type === 'radio'">
                                    <p><b>{{ q.question }}</b></p>
                                    <span v-if="q.answer == 'Not Answer'" color="error"><b>Answer:</b> <span
                                            class="text-danger">{{ q.answer }}</span></span>
                                    <span v-else><b>Answer:</b> {{ q.answer }}</span>
                                    <!-- <v-checkbox v-for="(  option, optionIndex  ) in   q.options  " :key="optionIndex"
                                        v-model="q.answer" :label="option" :value="option" readonly></v-checkbox> -->
                                </template>
                                <template v-else-if="q.type === 'dropdown'">
                                    <p><b>{{ q.question }}</b></p>
                                    <span v-if="q.answer == 'Not Answer'"><b>Answer:</b> <span class="text-danger">{{
                        q.answer }}</span></span>
                                    <span v-else><b>Answer:</b> {{ q.answer }}</span>
                                    <!-- <v-select class="" v-model="q.answer" :items="q.options" label="Select"
                                        readonly></v-select> -->

                                </template>
                                <template v-else-if="q.type === 'checkbox'">
                                    <p><b>{{ q.question }}</b></p>
                                    <span v-if="q.answer == 'Not Answer'" color="error"><b>Answer:</b> <span
                                            class="text-danger">{{ q.answer }}</span></span>
                                    <span v-else><b>Answer:</b> {{ q.answer }}</span>
                                    <!-- <v-checkbox v-model="q.answer" :label="q.label" readonly></v-checkbox>
                                    <v-checkbox v-for="(  option, optionIndex  ) in   q.options  " :key="optionIndex"
                                        :value="option" v-model="q.answer" :label="option" readonly></v-checkbox> -->
                                </template>

                            </v-col>
                        </v-row>
                    </div>

                </VCardText>
            </VCard>
        </VCol>
    </VRow>
</template>
<style lang="scss">
.text-danger {
    color: red;
}

.form-check-input[type=checkbox] {
    border-radius: 0.25em;
}

.form-check .form-check-input {
    float: left;
    margin-right: 0.5em;
}

.form-check-input {
    cursor: pointer;
}

.spinner-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100px;
    /* Set the height as needed */
}

.form-check-input {
    width: 1.2em;
    height: 1.2em;
    margin-top: 0.135em;
    vertical-align: top;
    background-color: #fff;
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    border: 2px solid #dbdade;
    appearance: none;
}

.form-check .form-check-input:checked,
.form-check .form-check-input[type=checkbox]:indeterminate {
    box-shadow: 0 0.125rem 0.25rem rgba(165, 163, 174, 0.3);
}

.form-check-input:checked[type=checkbox] {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='11' height='13' viewBox='0 0 15 14' fill='none'%3E%3Cpath d='M3.41667 7L6.33333 9.91667L12.1667 4.08333' stroke='%23fff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
}

.form-check-input:checked,
.form-check-input[type=checkbox]:indeterminate {
    background-color: #7367f0;
    border-color: #7367f0;
}

.form-check-input:checked {
    background-color: #7367f0;
    border-color: #7367f0;
}

.form-check-input[type=checkbox] {
    border-radius: 0.25em;
}
</style>
