<template>
    <OptionGroup
        :addAction="openModal"
        :options="optionsToDisplay"
        :addLabel="$t('Register.not_listed')"
        :help="help"
        :label="label"
        :nameBy="`name_${$i18n.locale}`"
        v-model:value="_value"
        limit="5"
    />
    <Modal @closed="closedModal" size="lg" ref="newSkillModal">
        <div
            class="container flex flex-col items-center justify-center w-full pb-5"
        >
            <FormKit
                form-class="w-full mt-5"
                name="category_form"
                type="form"
                @submit="submit"
                :actions="false"
                #default="{ state: { valid } }"
            >
                <FormKit
                    id="name"
                    name="name"
                    v-model="form.name_en"
                    type="text"
                    required
                    label="Name"
                    placeholder="Ex. Software Engineering"
                    validation="required|length:3,50"
                    validation-label="name"
                />
                <div class="flex items-center justify-end w-full">
                    <FormKit
                        :loading="form.processing"
                        :disabled="!valid || form.processing"
                        type="submit"
                    >
                        {{ $t("Register.save") }}
                    </FormKit>
                </div>
            </FormKit>
        </div>
    </Modal>
</template>

<script>
import OptionGroup from "@/components/Inputs/Selects/Checkboxes/Pills/OptionGroup";
import Modal from "@/components/General/FormModal.vue";
import { useForm } from "@inertiajs/inertia-vue3";
export default {
    components: {
        OptionGroup,
        Modal,
    },
    props: {
        value: {
            type: Array,
            required: true,
        },
        label: {
            type: String,
            default: "Skills",
        },
        help: {
            type: String,
            required: true,
        },
    },
    data() {
        return {
            options: [],
            optionsToDisplay: [],
            _value: [],
            form: {
                name_en: "",
                name_ar: "",
                processing: false,
            },
            loading: false,
        };
    },
    methods: {
        addSkill() {},
        fetch() {
            this.axios
                .post(route("skills.index"))
                .then((response) => {
                    this.options = response.data.skills;
                    this.options.forEach((skill) => {
                        if (
                            !this.optionsToDisplay.find(
                                (s) => s.id === skill.id
                            ) &&
                            (skill.verified || this._value.includes(skill.id))
                        )
                            this.optionsToDisplay.push(skill);
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        submit() {
            this.form.processing = true;
            this.form.name_ar = this.form.name_en;
            this.axios
                .post(route("skills.store"), this.form)
                .then((response) => {
                    // check if the skill already exists
                    if (!this._value.includes(response.data.skill.id))
                        this._value.push(response.data.skill.id);

                    if (
                        this.options.find(
                            (skill) => skill.id === response.data.skill.id
                        )
                    ) {
                        this.$page.props.flash.status =
                            "This skill already exists";

                        this.$refs.newSkillModal.close();
                        // return;
                    }

                    response.data.skill.verified = 1;
                    if (
                        !this.options.find(
                            (skill) => skill.id === response.data.skill.id
                        )
                    )
                        this.options.push(response.data.skill);
                    else {
                        this.options = this.options.map((skill) => {
                            if (skill.id === response.data.skill.id)
                                return response.data.skill;
                            return skill;
                        });
                    }

                    if (
                        !this.optionsToDisplay.find(
                            (skill) => skill.id === response.data.skill.id
                        )
                    )
                        this.optionsToDisplay.push(response.data.skill);

                    this.$refs.newSkillModal.close();
                })
                .catch((error) => {
                    console.log(error);
                })
                .finally(() => {
                    this.form.processing = false;
                    this.form.name_en = "";
                    this.form.name_ar = "";
                });
        },
        openModal() {
            this.$refs.newSkillModal.open();
        },
        closeModal() {
            this.$refs.newSkillModal.close();
        },
        closedModal() {
            this.form.name_en = "";
            this.form.name_ar = "";
        },
    },
    mounted() {
        this.fetch();
        this._value = this.value;
    },
    updated() {
        // make sure that no endless loop is created (value is an array)
        if (this._value !== this.value) {
            this._value = this.value;
        }
    },
    watch: {
        _value() {
            this.$emit("update:value", this._value);
        },
        // options() {
        //     this.options.forEach((skill) => {
        //         if (
        //             !this.optionsToDisplay.find(
        //                 (skill) => skill.id === skill.id
        //             )
        //         )
        //             this.optionsToDisplay.push(skill);
        //     });
        //     // this.optionsToDisplay = this.options.filter(
        //     //     (skill) => this._value.includes(skill.id) || skill.verified == 1
        //     // );
        // },
    },
};
</script>
