<template>
    <textboxQuestion
        v-model="selectedAccountName"
        customInputId="autocomplete"
        class="mb-4 mt-5"
        cmsWidgetName="InsuranceCoQuestionWidget"
        includeSearchIcon />
</template>

<script>
// Components
import textboxQuestion from "@/digital-components/textbox-question/textbox-question";

// Supporting files
import $ from "jquery";

// MAPPNG
const termMapping = [
    {
        term: "1ST",
        altTerm: "FIRST",
    },
    {
        term: "FIRST",
        altTerm: "1ST",
    },
    {
        term: "AAA",
        altTerm: "American",
    },
];

export default {
    name: "insurance-company-question",
    props: {
        originalList: Array,
        modelValue: String,
    },
    data() {
        return {
            selectedAccountName: "",
        };
    },
    computed: {
        selectedAccountNumber: {
            get: function () {
                return this.modelValue?.toString();
            },
            set: function (newValue) {
                this.$emit("update:modelValue", newValue); // send data up to v-model on parent, s/b account number
            },
        },
        searchableInsuranceCompanyList() {
            return this.originalList.map((insuranceCompany) => {
                insuranceCompany.altTerms = "";

                termMapping.forEach((matchingTerm) => {
                    if (
                        insuranceCompany.accountName
                            .toUpperCase()
                            .includes(matchingTerm.term.toUpperCase())
                    ) {
                        insuranceCompany.altTerms =
                            insuranceCompany.altTerms + matchingTerm.altTerm?.toUpperCase() + " ";
                    }
                });
                return insuranceCompany;
            });
        },
    },
    methods: {
        getParentAccountNumber(name) {
            const matchedItems = this.searchableInsuranceCompanyList?.filter((item) => {
                return item.accountName?.toString() === name.toString();
            });

            if (matchedItems.length > 0) {
                return matchedItems[0].parentAccountNumber;
            } else {
                console.error("Error locating accountNumber");
                return;
            }
        },
        getParentAccountName(number) {
            const matchedItems = this.searchableInsuranceCompanyList?.filter((item) => {
                return item.parentAccountNumber?.toString() === number.toString();
            });

            if (matchedItems.length > 0) {
                return matchedItems[0].accountName;
            } else {
                console.error("Error locating accountName");
                return;
            }
        },
        findMatches(request, response) {
            const matches = [];
            const term = request?.term?.toUpperCase();
            const nonPriorityMatches = [];

            this.searchableInsuranceCompanyList.forEach((company, index) => {
                if (
                    company.accountName.toUpperCase().indexOf(term) !== -1 ||
                    company.altTerms.toUpperCase().indexOf(term) !== -1
                ) {
                    matches.push(company.accountName);
                }
            });

            // Prioritize matched typed entries to top of list
            const priorityMatches = matches.filter((companyName, index) => {
                if (companyName.toUpperCase().indexOf(term) === 0) {
                    return companyName;
                } else {
                    nonPriorityMatches.push(companyName);
                }
            });

            const prioritizedMatches = [...priorityMatches, ...nonPriorityMatches];

            response(prioritizedMatches);
        },
        selectInsuranceCompany(parentAccountName) {
            // this runs upon user selection within jQueryUI Autocomplete
            if (!this.searchableInsuranceCompanyList) {
                console.error("No insurance companies found");
                return;
            }
            if (parentAccountName) {
                const parentAccountNumber = this.getParentAccountNumber(parentAccountName);
                this.selectedAccountNumber = parentAccountNumber;
                this.selectedAccountName = this.getParentAccountName(parentAccountNumber);
            } else {
                this.selectedAccountNumber = "";
                this.selectedAccountName = "";
            }
        },
    },
    mounted() {
        if (this.modelValue.length > 0) {
            this.selectedAccountName = this.getParentAccountName(this.modelValue?.toString());
        }

        const select = this.selectInsuranceCompany;
        setTimeout(() => {
            $("#autocomplete").autocomplete({
                source: this.findMatches,
                position: {
                    my: "left top+6",
                },
                minLength: 0, // Necessary to display fmenu when clearing input

                select: function (event, ui) {
                    select(ui.item.value);
                },
                change: function (event, ui) {
                    select(ui?.item?.value);
                },
            });
        }, 0);
    },
    components: {
        textboxQuestion,
    },
};
</script>

<style lang="scss">
ul {
    &.ui-autocomplete {
        position: absolute;
        list-style-type: none;
        margin: 0;
        padding: 0.25rem;
        background: $white;
        border: 1px solid $gray;
        border-radius: 0.25rem;
        height: auto;
        max-height: 50%;
        overflow: auto;
        li {
            &:hover,
            .ui-state-active {
                background-color: $gray-100;
                cursor: pointer;
            }
            .ui-menu-item-wrapper {
                border: 1px solid transparent;
                border-radius: 2px;
                padding-left: 0.25rem;
                span {
                    font-weight: 600;
                }
                &.ui-state-active {
                    border: 1px solid $gray-200;
                    border-radius: 2px;
                    font-weight: 600;
                }
            }
        }
    }
}
.ui-helper-hidden-accessible {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}
</style>
