Vue.component('patientBpTrack', {
    props: ['routes','events','parent','initialRecords','today'],

    data() {
        const initialProvided = Array.isArray(this.initialRecords);
        const initialList = initialProvided ? this.initialRecords.slice() : [];
        const seedDate = this.today || null;
        return {
            records: initialList,
            todayDate: seedDate,
            hasLoaded: initialProvided,
            loading: false,
            add: false,
            errors: {},
            success: false,
            display: 3,
            defaultBpRecord: { id: null, low: '', high: '', heart_rate: '' },
            record: {},
            deleteIndex: -1,
            showingAll: false,
            eventIndex: 0,
            reviewID: null,
        };
    },

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

    watch: {
        initialRecords: {
            immediate: true,
            handler(list) {
                if (!Array.isArray(list)) return;
                this.records = list.slice();
                this.hasLoaded = true;
                this.loading = false;
                this.bindImageModal();
            }
        },
        today: {
            immediate: true,
            handler(value) {
                if (value) {
                    this.todayDate = value;
                }
            }
        },
        events(stack) {
            for (let i = this.eventIndex; i < stack.length; i++) {
                const event = stack[i];
                if (event.name === 'filesUpdated') this.load(true);
                if (event.name === 'initReview') { this.reviewID = event.data.reviewId; this.load(true); }
                if (event.name === 'bpTrackUpdated') this.load(true);
            }
            this.eventIndex = stack.length;
        }
    },

    computed: {
        canShowAll() {
            const list = Array.isArray(this.records) ? this.records : [];
            if (!list.length) return false;
            if (this.showingAll) return false;
            return list.length > this.display;
        }
    },

    methods: {
        /*init() {
            this.record = { ...this.defaultBpRecord };
            if (this.parent !== 'review') this.load();
        },*/
        init(){
            this.record = { ...this.defaultBpRecord };
            if (this.parent !== 'review' && !this.hasLoaded) this.load(true);
        },

        load(force = false) {
            const params = (this.parent === 'review' && this.reviewID > 0) ? { review_id: this.reviewID } : {};
            if (!force && this.loading) {
                return;
            }

            if (!params.review_id) {
                const cached = (!force && this.consumeBootstrap)
                    ? this.consumeBootstrap('admin-patient-bp-track-load')
                    : null;
                if (cached) {
                    const list = Array.isArray(cached.bpTrack) ? cached.bpTrack : [];
                    const today = cached?.todayDate ?? null;
                    this.records   = list;
                    this.todayDate = today;
                    this.loading   = false;
                    this.hasLoaded = true;
                    if (typeof this.cacheBootstrap === 'function') {
                        this.cacheBootstrap('admin-patient-bp-track-load', {
                            bpTrack: list.slice(),
                            todayDate: today,
                        });
                    }
                    if (window.PatientProfileBootstrap) {
                        window.PatientProfileBootstrap.bp = list.slice();
                        window.PatientProfileBootstrap.todayDate = today;
                    }
                    this.bindImageModal();
                    return;
                }
            }

            this.loading = true;
            const vm = this;

            this.$http.post(this.routes['admin-patient-bp-track-load'], params)
                .then((response) => {
                    let payload = response.data;
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); } catch (e) { console.error('Invalid JSON (bp load):', e, payload); payload = {}; }
                    }

                    const list = Array.isArray(payload?.bpTrack) ? payload.bpTrack : [];
                    const today = payload?.todayDate ?? null;
                    vm.records   = list;
                    vm.todayDate = today;
                    vm.loading   = false;
                    vm.hasLoaded = true;
                    if (typeof vm.cacheBootstrap === 'function') {
                        vm.cacheBootstrap('admin-patient-bp-track-load', {
                            bpTrack: list.slice(),
                            todayDate: today,
                        });
                    }
                    if (window.PatientProfileBootstrap) {
                        window.PatientProfileBootstrap.bp = list.slice();
                        window.PatientProfileBootstrap.todayDate = today;
                    }
                    vm.bindImageModal();
                })
                .catch((err) => {
                    console.error('BP load failed:', err);
                    this.loading = false;
                    this.records = [];
                });
        },

        addRecord() {
            this.add = true;
            this.record = { ...this.defaultBpRecord };
            // seed date input
            const el = $('#bpTrackDate' + this.parent);
            if (el && el.length) el.val(this.todayDate || '');
        },

        cancel() {
            this.add = false;
            this.errors = {};
            this.success = false;
            this.record = { ...this.defaultBpRecord };
            // clear file input if any
            const fileEl = $('#bpFile' + this.parent);
            if (fileEl && fileEl.length) fileEl.val('');
        },

        store() {
            if (this.loading) return;

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

            // Pull date from the datepicker input
            const dateVal = $('#bpTrackDate' + this.parent).val();
            this.record.date_provided = (dateVal && dateVal.trim()) ? dateVal.trim() : (this.todayDate || '');

            // Build multipart form-data; DO NOT set Content-Type manually
            const fd = new FormData();
            fd.append('id', this.record.id == null ? '' : this.record.id);
            fd.append('low', this.record.low == null ? '' : this.record.low);
            fd.append('high', this.record.high == null ? '' : this.record.high);
            fd.append('heart_rate', this.record.heart_rate == null ? '' : this.record.heart_rate);
            fd.append('date_provided', this.record.date_provided || '');

            if (this.reviewID) fd.append('review_id', this.reviewID);

            const fileEl = document.getElementById('bpFile' + this.parent);
            if (fileEl && fileEl.files && fileEl.files[0]) {
                fd.append('file', fileEl.files[0]);
            }

            const vm = this;
            this.$http.post(this.routes['admin-patient-bp-track-store'], fd, {
                emulateJSON: false, // important for FormData
                // headers: {}  <-- let the browser set multipart boundary
            })
                .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.record = { ...vm.defaultBpRecord };
                    vm.add = false;

                    // Refresh list immediately
                    vm.load(true);
                    vm.emitEvent('bpTrackUpdated');
                })
                .catch((err) => {
                    console.error('BP store failed:', err);
                    this.loading = false;
                    this.errors.general = 'Unable to save. Please try again.';
                });
        },

        showConfirmDeletion(index) { this.deleteIndex = index; },

        deleteRecord(id) {
            if (this.loading) return;

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

            const vm = this;

            this.$http.post(this.routes['admin-patient-bp-track-delete'], { 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;
                        vm.loading = false;
                        return;
                    }
                    if (payload.success) vm.success = payload.success;

                    vm.showConfirmDeletion(-1);
                    vm.load(true);
                    vm.emitEvent('bpTrackUpdated');
                })
                .catch((err) => {
                    console.error('BP delete failed:', err);
                    this.loading = false;
                });
        },

        showAll() {
            this.showingAll = true;
            this.bindImageModal();
        },

        bindImageModal() {
            this.$nextTick(function () {
                $('.bpTrackImage').mtcOverlay();
            });
        },

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