Vue.component('patientFlags', {

    props: [
        'routes',
        'initialFlags'
    ],

    data: function() {
        const initialProvided = Array.isArray(this.initialFlags);
        const initial = initialProvided ? this.initialFlags.slice() : [];
        return {
            flags: initial,
            hasLoaded: initialProvided,
            loading: false,
            add: false,
            errors: {},
            success: false,
            display: 5,
            flag: '',
            isTask: false,
            deleteIndex: -1,
        };
    },

    mounted: function() {
        if (!this.hasLoaded) this.load();
    },

    watch: {
        initialFlags: {
            immediate: true,
            handler(list) {
                if (!Array.isArray(list)) {
                    return;
                }
                this.flags = list.slice();
                this.hasLoaded = true;
                this.loading = false;
            }
        }
    },

    methods: {
        init() {
            this.load();
        },
        load(force = false) {
            if (this.loading && !force) {
                return;
            }

            this.loading = true;
            let vm = this;

            const applyPayload = (payload) => {
                const list = Array.isArray(payload?.flags) ? payload.flags : [];
                vm.flags = list.slice();
                vm.loading = false;
                vm.hasLoaded = true;
                if (typeof vm.cacheBootstrap === 'function') {
                    vm.cacheBootstrap('admin-member-notes-load-flags', { flags: list.slice() });
                }
                if (window.PatientProfileBootstrap) {
                    window.PatientProfileBootstrap.flags = list.slice();
                }
                if (vm.bootstrap && typeof vm.bootstrap === 'object') {
                    if (typeof vm.$set === 'function') {
                        vm.$set(vm.bootstrap, 'flags', list.slice());
                    } else {
                        vm.bootstrap.flags = list.slice();
                    }
                }
            };

            const cached = (!force && this.consumeBootstrap)
                ? this.consumeBootstrap('admin-member-notes-load-flags')
                : null;
            if (cached) {
                applyPayload(cached);
                return;
            }

            this.$http.post(this.routes['admin-member-notes-load-flags'], [])
                .then((response) => {

                    let payload = response.data;
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); } catch (e) { console.error('flags load invalid JSON', e, payload); payload = {}; }
                    }
                    applyPayload(payload);
                })
                .catch(err => {
                    console.error('flags load failed', err);
                    this.loading = false;
                    this.flags = [];
                });
        },
        addFlag() {
            this.add = true;
        },
        cancel() {
            this.add = false;
        },
        store() {
            if (this.loading) return;

            this.errors = {};
            this.success = false;
            this.loading = true;

            const vm = this;

            this.$http.post(this.routes['admin-member-notes-store'], {
                note: this.flag,
                isTask: this.isTask ? '1' : '0',
                flagDue: $('#flagDue').val(),
                isFlag: 1,
            })
                .then((response) => {
                    let payload = response.data;
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); } catch { payload = {}; }
                    }

                    if (payload.errors) {
                        vm.errors = payload.errors;
                        vm.loading = false;
                        return;
                    }
                    if (payload.success) {
                        vm.success = payload.success;
                    }
                    vm.flag = '';
                    vm.add = false;
                    vm.load(true);
                    vm.emitEvent('flagsChanged');
                })
                .catch(err => {
                    console.error('flag store failed', err);
                    this.loading = false;
                });
        },
        showConfirmDeletion(index) {
            this.deleteIndex = index;
        },
        deleteFlag(id) {
            if (this.loading) return;
            this.errors = {};
            this.success = false;
            this.loading = true;

            const vm = this;

            this.$http.post(this.routes['admin-member-notes-delete-flag'], { id })
                .then((response) => {
                    let payload = response.data;
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); } catch { payload = {}; }
                    }

                    if (payload.errors) {
                        vm.errors = payload.errors;
                        this.loading = false;
                        return;
                    }
                    if (payload.success) {
                        vm.success = payload.success;
                    }
                    vm.showConfirmDeletion(-1);
                    vm.load(true);
                    vm.emitEvent('flagsChanged');
                })
                .catch(err => {
                    console.error('flag delete failed', err);
                    this.loading = false;
                });
        },
        toggleStatus(id, status) {
            if (this.loading) return;
            this.errors = {};
            this.loading = true;

            const vm = this;

            this.$http.post(this.routes['admin-member-notes-toggle-flag-status'], { id, status })
                .then((response) => {
                    let payload = response.data;
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); } catch { payload = {}; }
                    }

                    this.loading = false;

                    if (payload.errors) {
                        vm.errors = payload.errors;
                        return;
                    }
                    if (payload.success) {
                        const list = Array.isArray(vm.flags) ? vm.flags : [];
                        for (let i = 0; i < list.length; i++) {
                            if (String(list[i].id) === String(id)) {
                                vm.$set(list[i], 'status', status);
                                break;
                            }
                        }
                        vm.flags = list; // ensure stays an array
                        if (typeof vm.cacheBootstrap === 'function') {
                            vm.cacheBootstrap('admin-member-notes-load-flags', { flags: list.slice() });
                        }
                        if (window.PatientProfileBootstrap) {
                            window.PatientProfileBootstrap.flags = list.slice();
                        }
                        vm.emitEvent('flagsChanged');
                    }
                })
                .catch(err => {
                    console.error('toggle flag failed', err);
                    this.loading = false;
                });
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        },
    },
});
