<template>
    <div class="category-question-manager" v-cloak>

        <div class="mb-4 flex items-center justify-between flex-wrap gap-2">
            <div class="flex items-center gap-2">
                <div class="relative">
                    <select
                        v-model="filterStatus"
                        class="appearance-none bg-white border border-gray-300 rounded-sm text-xs text-gray-700 pl-3 pr-8 py-1.5 focus:outline-none focus:shadow-outline-blue focus:border-blue-300"
                    >
                        <option value="">All Statuses</option>
                        <option value="active">Active</option>
                        <option value="pending">Pending</option>
                        <option value="inactive">Inactive</option>
                    </select>
                    <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="fill-current h-3 w-3">
                            <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"></path>
                        </svg>
                    </div>
                </div>
            </div>
            <button
                class="inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs leading-5 font-medium rounded-sm text-gray-700 bg-white hover:text-gray-500 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 active:text-gray-800 active:bg-gray-50 transition duration-150 ease-in-out"
                @click.prevent="openAttachModal"
            >
                Attach Question
            </button>
        </div>

        <div v-if="filteredItems && filteredItems.length" :class="['has-items', state]">
            <draggable
                :list="items"
                handle=".drag-handle"
                @update="updateSortOrder"
            >
                <transition-group name="list" tag="div">
                    <category-question-item
                        v-for="item in filteredItems"
                        :key="item.id"
                        :item="item"
                    >
                    </category-question-item>
                </transition-group>
            </draggable>
        </div>
        <div v-else :class="['no-items', state]">
            <v-card>
                <div class="message text-center">
                    <div class="message-text font-semibold">
                        No questions attached to this category.
                    </div>
                </div>
            </v-card>
        </div>

        <div v-if="message && messageType"
             class="rounded-sm p-4 mt-4 border"
             :class="{
                'bg-red-100 border-red-400' : messageType === 'error',
                'bg-green-100 border-green-400' : messageType === 'success',
            }"
        >
            <div class="flex">
                <div class="ml-3">
                    <p class="text-sm leading-5"
                       :class="{
                            'text-red-800' : messageType === 'error',
                            'text-green-800' : messageType === 'success',
                        }"
                    >{{ message }}</p>
                </div>
            </div>
        </div>

        <modal
            ref="attachModal"
            :show-overflow="true"
            btn-primary-text="Attach"
            @btnPrimaryClicked="attachQuestion"
            @btnSecondaryClicked="closeModal"
        >
            <h3 slot="modal_title" class="text-lg leading-6 font-medium text-gray-900">
                Attach Question
            </h3>

            <div slot="modal_content">
                <div class="form-group">
                    <label class="text-sm leading-5 font-medium text-gray-500">Question</label>

                    <div v-if="unattachedQuestions.length">
                        <div class="mt-1 relative rounded-sm shadow-sm">
                            <select
                                class="form-input block w-full rounded-sm sm:text-sm sm:leading-5 pr-10"
                                v-model="selectedQuestionId"
                            >
                                <option value="">Select a question...</option>
                                <option v-for="question in unattachedQuestions" :key="question.id" :value="question.id">
                                    {{ question.name }}
                                </option>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="fill-current h-4 w-6">
                                    <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"></path>
                                </svg>
                            </div>
                        </div>
                        <p v-if="hasErrors && !selectedQuestionId" class="mt-1 text-sm text-red-600">Please select a question</p>
                    </div>

                    <div v-else class="mt-1 rounded-sm border-2 border-dashed border-gray-300 p-6 text-center">
                        <p class="text-sm text-gray-500">No available questions found.</p>
                        <p class="mt-1 text-xs text-gray-400">All questions are already attached to this category.</p>
                    </div>
                </div>

                <div v-if="modalError" class="rounded-sm p-3 mt-4 bg-red-100 border border-red-400">
                    <p class="text-sm text-red-800">{{ modalError }}</p>
                </div>
            </div>

            <div v-if="!unattachedQuestions.length" slot="modal_footer">
                <button
                    class="w-full text-center px-4 py-2 text-sm leading-5 font-medium rounded-sm transition duration-150 ease-in-out border border-gray-300 text-gray-700 bg-white md:w-auto hover:text-gray-500 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 active:text-gray-800 active:bg-gray-50"
                    type="button"
                    @click="closeModal"
                >
                    Close
                </button>
            </div>
        </modal>
    </div>
</template>


<script>
import CategoryQuestionItem from "./CategoryQuestionItem";
import Modal from "../Modal";
import draggable from "vuedraggable";

export default {
    name : "CategoryQuestionManager",
    components : {
        CategoryQuestionItem,
        Modal,
        draggable,
    },
    props : {
        category : {type : Object, required : true},
        resourceUrl : {type : String, required : true},
    },
    data() {
        return {
            state : 'loading',
            hasErrors : false,
            modalError : null,

            message : null,
            messageType : null,

            filterStatus : '',

            items : [],
            availableQuestions : [],
            selectedQuestionId : '',
        }
    },
    computed : {
        unattachedQuestions() {
            let attachedIds = this.items.map(item => item.id);
            return this.availableQuestions.filter(q => !attachedIds.includes(q.id));
        },
        filteredItems() {
            if (!this.filterStatus) {
                return this.items;
            }
            return this.items.filter(item => item.status === this.filterStatus);
        },
    },
    methods : {
        openAttachModal() {
            this.hasErrors = false;
            this.modalError = null;
            this.selectedQuestionId = '';
            this.$refs.attachModal.showModal();
        },
        closeModal() {
            this.$refs.attachModal.closeModal();
        },

        attachQuestion() {
            this.hasErrors = false;

            if (!this.selectedQuestionId) {
                this.hasErrors = true;
                return;
            }

            this.modalError = null;
            window.axios
                .post(`${this.resourceUrl}/attach`, {
                    question_id : this.selectedQuestionId,
                })
                .then((response) => {
                    this.items = response.data.data;
                    this.closeModal();
                    this.resetMessage();
                })
                .catch(e => {
                    let errorMessage = e.response?.data?.message || e.message;
                    this.modalError = errorMessage;
                });
        },

        detachQuestion(args) {
            if (!args.item) return;

            window.axios
                .post(`${this.resourceUrl}/${args.item.id}/detach`)
                .then((response) => {
                    this.items = response.data.data;
                    this.resetMessage();
                })
                .catch(e => {
                    this.showError(e.response?.data?.message || e.message);
                });
        },

        updateSortOrder() {
            let questions = this.items.map((item, index) => ({
                question_id : item.id,
                sort_order : index + 1,
            }));

            this.items.forEach((item, index) => {
                item.sort_order = index + 1;
            });

            window.axios
                .post(`${this.resourceUrl}/reorder`, {questions : questions})
                .then((response) => {
                    this.items = response.data.data;
                })
                .catch(e => {
                    this.showError(e.response?.data?.message || e.message);
                });
        },

        fetchItems() {
            this.state = 'loading';

            window.axios
                .get(this.resourceUrl)
                .then((response) => {
                    this.items = response.data.data || [];
                    this.state = this.items.length ? 'ready' : 'no-data';
                })
                .catch(e => {
                    this.showError(e.response?.data?.message || e.message);
                });
        },

        fetchAvailableQuestions() {
            window.axios
                .get('/api/questions')
                .then((response) => {
                    this.availableQuestions = response.data.data || [];
                })
                .catch(() => {});
        },

        resetMessage() {
            this.message = null;
            this.messageType = null;
        },
        showError(message) {
            this.state = 'error';
            this.message = message;
            this.messageType = 'error';
        },
    },
    mounted() {
        this.fetchItems();
        this.fetchAvailableQuestions();

        window.EventBus.$on('categoryQuestion:detachItem', (args) => this.detachQuestion(args));
    },
    beforeDestroy() {
        window.EventBus.$off('categoryQuestion:detachItem');
    }
}
</script>
