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

    data() {
        const initialProvided = Array.isArray(this.initialRecords);
        const initialList = initialProvided ? this.initialRecords.slice() : [];
        return {
            records: initialList,
            loading: false,
            add: false,
            errors: {},
            success: false,
            display: 5,
            defaultWeightRecord: {
                id: null,
                metric: 1,
                heightCm: '',
                heightFt: '',
                heightIn: '',
                weightKg: '',
                weightSt: '',
                weightLb: '',
            },
            record: {},
            deleteIndex: -1,
            todayDate: this.today || null,
            showingAll: false,
            eventIndex: 0,
            reviewID: null,
            hasLoaded: initialProvided,
        };
    },

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

    watch: {
        initialRecords: {
            immediate: true,
            handler(list) {
                if (!Array.isArray(list)) return;
                this.records = list.slice();
                this.hasLoaded = true;
                this.loading = false;
            }
        },
        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 === 'initReview') {
                    this.reviewID = event.data.reviewId;
                    this.load(true);
                }
                if (event.name === 'weightTrackUpdated') {
                    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.defaultWeightRecord };
            if (this.parent !== 'review' && !this.hasLoaded) {
                this.load(true);
                return;
            }
        },

        // cm → [ft, in]
        cmToFtIn(cm) {
            const n = Number(cm);
            if (!isFinite(n) || n <= 0) return ['', ''];
            const totalIn = n / 2.54;
            const ft = Math.floor(totalIn / 12);
            const inch = Math.round(totalIn - ft * 12);
            return [String(ft), String(inch)];
        },

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

            const fromPayload = (payload) => {
                const list       = Array.isArray(payload?.weightTrack) ? payload.weightTrack : [];
                const today      = payload?.todayDate ?? null;
                const heightCm   = Number(payload?.height ?? 0) || 0;
                let heightImp    = Array.isArray(payload?.heightImperial) ? payload.heightImperial : null;
                if (!heightImp || heightImp.length < 2) {
                    heightImp = this.cmToFtIn(heightCm);
                }

                this.records = list;
                this.todayDate = today;
                this.defaultWeightRecord = {
                    ...this.defaultWeightRecord,
                    heightCm: heightCm ? String(heightCm) : '',
                    heightFt: heightImp[0] ?? '',
                    heightIn: heightImp[1] ?? '',
                };
                this.loading = false;
                this.hasLoaded = true;

                if (typeof this.cacheBootstrap === 'function') {
                    this.cacheBootstrap('admin-patient-weight-track-load', {
                        weightTrack: list.slice(),
                        todayDate: today,
                        height: heightCm,
                        heightImperial: Array.isArray(heightImp) ? heightImp.slice() : heightImp,
                    });
                }
                if (window.PatientProfileBootstrap) {
                    window.PatientProfileBootstrap.weightTrack = list.slice();
                    window.PatientProfileBootstrap.todayDate = today;
                }
            };

            if (!params.review_id) {
                const cached = (!force && this.consumeBootstrap)
                    ? this.consumeBootstrap('admin-patient-weight-track-load')
                    : null;
                if (cached) {
                    fromPayload(cached);
                    return;
                }
            }

            this.loading = true;
            const vm = this;

            this.$http.post(this.routes['admin-patient-weight-track-load'], params)
                .then((response) => {
                    let payload = response.data;

                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); }
                        catch (e) { console.error('Invalid JSON from weight-track-load:', e, payload); payload = {}; }
                    }

                    fromPayload(payload);
                })
                .catch((err) => {
                    console.error('Weight track load failed:', err);
                    this.loading = false;
                    this.records = [];
                });
        },

        addRecord() {
            this.add = true;
            this.record = { ...this.defaultWeightRecord };
            $('#weightTrackDate' + this.parent).val(this.todayDate || '');
        },

        cancel() {
            this.add = false;
        },

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

            this.record.date_provided = $('#weightTrackDate' + this.parent).val();
            this.record.review_id = this.reviewID;

            const vm = this;

            this.$http.post(this.routes['admin-patient-weight-track-store'], this.record)
                .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.defaultWeightRecord };
                    vm.add = false;
                    vm.emitEvent('weightTrackUpdated');
                })
                .catch((err) => {
                    console.error('Weight track store failed:', err);
                    this.loading = false;
                });
        },

        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-weight-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.emitEvent('weightTrackUpdated');
                })
                .catch((err) => {
                    console.error('Weight track delete failed:', err);
                    this.loading = false;
                });
        },

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

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