<script setup>
import axios from '@axios';
import {
    requiredValidator
} from '@validators';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const isMobile = ref(window.innerWidth <= 768); // Assuming mobile width is less than or equal to 768px

const currentDialoagkey = ref('')
const isTonalSnackbarVisible = ref(false)
const patientResponse = ref(false)
const isLoadingVisible = ref(false)
const questionForm = ref()
const answers = ref([]);
const isDialogVisible = ref(false)
const questionAnswer = ref([]);
const finalArray = ref([]);
onMounted(async () => {
    await getPatientMedicalHistory();
    isLoadingVisible.value = true;

    finalArray.value = getFinalArray(questions.value, questionAnswer.value);
    console.log("finalArray", finalArray);
    isLoadingVisible.value = false;
});
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 Applicable"],
    },
    {
        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 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
            });
        }
    });

    return finalArray;
};
const validateQuestion = async () => {
    const { valid: isValid } = await questionForm.value?.validate();
    console.log('isValid ', isValid);
    if (isValid)
        saveAnswers()
};

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 saveAnswers = () => {
    isLoadingVisible.value = true;
    const patient_id = localStorage.getItem('patient_id');
    const jsonData = {
        questions: questions.value.reduce((accumulator, question, index) => {
            const answerValue = answers.value[question.question_key];

            if (answerValue !== undefined) {
                accumulator.push({
                    question_key: question.question_key,
                    type: question.type,
                    answer: answerValue,
                });
            }

            return accumulator;
        }, []),
    };
    let qaData = Array({ 'answers': jsonData.questions });
    console.log('answers ', JSON.stringify(qaData));
    // You can send the jsonData to your server or use it as needed
    axios.post('/api/medical-history-question-post/' + patient_id,
        {
            answers: jsonData.questions
        }
    )
        .then(response => {
            console.log('answer api', response.data)
            // console.log(chooseDate);
            isLoadingVisible.value = false;
            router.replace(route.query.to && route.query.to != '/additional-information' ? String(route.query.to) : '/profile')
        })
        .catch(error => {
            isLoadingVisible.value = false;
            // console.error(error);
        });
};
</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>

    <div class="pb-sm-5 pb-2 rounded-top">
        <VContainer>
            <div class="auth-wrapper align-center justify-center">

                <VRow class="">
                    <VCol cols="12" md="12">
                        <!-- 👉 Title and subtitle -->
                        <div class="text-primary">
                            <h3 class="text-primary">
                                Update Medical History
                            </h3>
                        </div>
                    </VCol>
                    <VCol cols="12" md="12">
                        <v-card flat>
                            <VForm ref="questionForm" @submit.prevent="() => { }">
                                <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>{{ q.question }}</b></p>
                                                <v-text-field class="col-md-4" v-model="q.answer"
                                                    :rules="[requiredValidator]" />
                                            </template>
                                            <template v-else-if="q.type === 'radio'">
                                                <p><b>{{ q.question }}</b></p>
                                                <v-checkbox v-for="( option, optionIndex  ) in   q.options  "
                                                    :key="optionIndex" v-model="answers[q.answer]" :label="option"
                                                    :value="option"></v-checkbox>
                                            </template>
                                            <template v-else-if="q.type === 'dropdown'">
                                                <p><b>{{ q.question }}</b></p>
                                                <v-select class="" v-model="answers[q.answer]" :items="q.options"
                                                    label="Select"></v-select>

                                            </template>
                                            <template v-else-if="q.type === 'checkbox'">
                                                <p><b>{{ q.question }}</b></p>
                                                <v-checkbox v-model="answers[q.answer]" :label="q.label"></v-checkbox>
                                                <v-checkbox v-for="(  option, optionIndex  ) in   q.options  "
                                                    :key="optionIndex" :value="option" v-model="answers[q.answer]"
                                                    :label="option"></v-checkbox>
                                            </template>
                                        </v-col>
                                    </v-row>
                                </div>


                                <div class="text-center mb-2">
                                    <VBtn type="submit"
                                        class="btn btn-primary d-grid waves-effect waves-light text-center"
                                        color="primary" variant="flat" @click="validateQuestion">
                                        Update</VBtn>
                                </div>


                            </VForm>

                        </v-card>
                    </VCol>
                </VRow>
            </div>
        </VContainer>
    </div>

</template>
<style lang="scss">
.card-title {
    font-family: "Public Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
}

.v-list-item-title {
    white-space: inherit !important;
    ;
}

.v-list {
    min-height: 168px;
}

@media (min-width: 320px) and (max-width: 768px) {
    .v-container {
        padding: 0px !important;
    }

    .auth-wrapper {
        padding: 0px !important;
    }

    .input-width {
        max-width: 100% !important;
    }
}

// .input-width {
//     max-width: 50%;
// }

.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;
}

.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>
