const defaultTreatment = {
    id: null,
    item_id: null,
    date_from: '',
    date_to: '',
    product: '',
    notes: '',
};

Vue.component('editPatientTreatment', {
    props: ['routes','editTreatment','treatmentData'],

    data() {
        return {
            treatment: Object.assign({}, defaultTreatment),
            loading: false,
            errors: {},              // always an object
            foundItems: [],          // always an array
            itemQuery: '',
            product: null,
            deletePrompt: false,
            _itemsSearchTimer: null,
        };
    },

    mounted() { this.init(); },

    computed: {
        hasResults() {
            return Array.isArray(this.foundItems) && this.foundItems.length > 0;
        }
    },

    watch: {
        treatmentData(treatment) {
            if (treatment && typeof treatment.id !== 'undefined') {
                this.treatment = Object.assign({}, defaultTreatment, treatment);
                this.product   = treatment.item || null;
                this.deletePrompt = false;
                $('#treatmentDateFrom').val(treatment.date_from || '');
                $('#treatmentDateTo').val(treatment.date_to || '');
            } else {
                this.treatment = Object.assign({}, defaultTreatment);
                this.product = null;
                this.deletePrompt = false;
            }
        }
    },

    methods: {
        init() {},

        firstError(key) {
            const val = this.errors && this.errors[key];
            if (!val) return '';
            return Array.isArray(val) ? (val[0] || '') : val;
        },

        cancel() {
            $('.overlayCloseButton').trigger('click');
        },

        store() {
            if (this.loading) return;
            this.errors = {};

            if (!this.product || !this.product.id) {
                this.errors = { item_id: ['Please select a product'] };
                return;
            }

            this.loading = true;

            const payload = {
                ...this.treatment,
                item_id:  this.product.id,
                size_id:  this.product.size_id ?? null,
                date_from: $('#treatmentDateFrom').val() || null,
                date_to:   $('#treatmentDateTo').val() || null,
            };

            this.$http.post(this.routes['admin-patient-treatments-store'], payload)
                .then(({ data }) => {
                    this.loading = false;
                    if (data && data.errors) {
                        this.errors = data.errors || {};
                        return;
                    }
                    this.errors = {};
                    this.emitEvent('treatmentSaved');
                    $('.overlayCloseButton').trigger('click');
                })
                .catch(() => {
                    this.loading = false;
                    this.errors = { _general: ['Unable to save treatment. Please try again.'] };
                });
        },

        debouncedSearchItems() {
            clearTimeout(this._itemsSearchTimer);
            this._itemsSearchTimer = setTimeout(() => {
                const q = (this.itemQuery || '').trim();
                if (q.length < 3) { this.foundItems = []; return; }
                this.searchItems();
            }, 350);
        },

        searchItems() {
            const vm = this;
            this.$http.post(this.routes['admin-products-search'], {
                query: (this.itemQuery || '').trim(),
            })
                .then((response) => {
                    // axios-style: response.data; vue-resource: response.body
                    let data = response && (response.data ?? response.body);

                    // If backend sends text/plain, coerce to JSON
                    if (typeof data === 'string') {
                        try { data = JSON.parse(data); } catch (e) { data = {}; }
                    }

                    // Be liberal in what we accept:
                    const items = Array.isArray(data?.items) ? data.items : [];

                    // Populate results; do NOT rely solely on "success"
                    vm.foundItems = items;
                    vm.errors = items.length ? {} : (data?.errors || {});
                })
                .catch(() => {
                    vm.foundItems = [];
                    vm.errors = { _general: ['Search failed. Please try again.'] };
                });
        },


        selectItem(item) {
            this.$set(this, 'product', item);
            this.clearItemSearch();
            $('#itemQuery').focus();
        },

        clearItemSearch() {
            this.itemQuery = '';
            this.foundItems = [];
        },

        resetProduct() {
            this.product = null;
        },

        deleteAction() {
            if (!this.deletePrompt) {
                this.deletePrompt = true;
                return;
            }
            this.deleteTreatment();
        },

        deleteTreatment() {
            this.loading = true;
            const vm = this;
            this.$http.post(this.routes['admin-patient-treatments-delete'], this.treatment)
                .then(() => {
                    this.loading = false;
                    vm.emitEvent('treatmentDeleted');
                    $('.overlayCloseButton').trigger('click');
                })
                .catch(() => {
                    this.loading = false;
                    this.errors = { _general: ['Failed to delete treatment.'] };
                });
        },

        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        },
    },
});
