import { getCsrfToken } from '../helpers';

export function registerBookingSopPage(Alpine) {
    Alpine.data('sopApp', () => ({
        phases: [],
        activePhase: 0,
        stepActiveTplMap: {},
        substepActiveTplMap: {},
        canEdit: false,

        editStep: null,
        editTab: 'info',
        editForm: {
            name: '',
            desc: '',
            note: '',
            tip: '',
            templates: [],
            checklist_items: [],
        },
        saving: false,

        get currentPhase() {
            return this.phases[this.activePhase] || null;
        },

        getPhaseColumns(phaseIndex) {
            if (phaseIndex === 0) {
                return [
                    { colIndex: 0, steps: this.phases[0]?.steps?.slice(0, 2) || [], subSteps: [] },
                    { colIndex: 1, steps: this.phases[0]?.steps?.slice(2, 3) || [], subSteps: [] },
                    { colIndex: 2, steps: this.phases[1]?.steps?.slice(0, 2) || [], subSteps: [] },
                ];
            }
            if (phaseIndex === 1) {
                return [
                    { colIndex: 0, steps: this.phases[1]?.steps?.slice(2, 3) || [], subSteps: [] },
                    { colIndex: 1, steps: this.phases[1]?.steps?.slice(3, 4) || [], subSteps: [] },
                    { colIndex: 2, steps: this.phases[1]?.steps?.slice(4, 5) || [], subSteps: [] },
                ];
            }
            return [];
        },

        stepActiveTpl(stepId) {
            return this.stepActiveTplMap['step-' + stepId] || 0;
        },

        setStepActiveTpl(stepId, ti) {
            this.stepActiveTplMap['step-' + stepId] = ti;
            this.saveState();
        },

        substepActiveTpl(ssi) {
            return this.substepActiveTplMap['substep-' + ssi] || 0;
        },

        setSubstepActiveTpl(ssi, ti) {
            this.substepActiveTplMap['substep-' + ssi] = ti;
            this.saveState();
        },

        init() {
            this.phases = window.__sopPhases || [];
            this.canEdit = window.__sopCanEdit || false;
            const saved = localStorage.getItem('sop_state_v2');
            if (saved) {
                try {
                    const parsed = JSON.parse(saved);
                    if (typeof parsed.activePhase === 'number' && parsed.activePhase < this.phases.length) {
                        this.activePhase = parsed.activePhase;
                    }
                    if (parsed.stepActiveTplMap) {
                        this.stepActiveTplMap = parsed.stepActiveTplMap;
                    }
                    if (parsed.substepActiveTplMap) {
                        this.substepActiveTplMap = parsed.substepActiveTplMap;
                    }
                } catch (e) { }
            }
        },

        selectPhase(pi) {
            this.activePhase = pi;
            this.stepActiveTplMap = {};
            this.substepActiveTplMap = {};
            this.saveState();
        },

        saveState() {
            try {
                localStorage.setItem('sop_state_v2', JSON.stringify({
                    activePhase: this.activePhase,
                    stepActiveTplMap: this.stepActiveTplMap,
                    substepActiveTplMap: this.substepActiveTplMap,
                }));
            } catch (e) { }
        },

        copyTpl(id, btn) {
            var el = document.getElementById(id);
            if (!el) return;
            navigator.clipboard.writeText(el.innerText).then(function () {
                btn.classList.add('is-copied');
                setTimeout(function () {
                    btn.classList.remove('is-copied');
                }, 1500);
            });
        },

        openEditModal(step) {
            this.editStep = step;
            this.editTab = 'info';
            this.editForm = {
                name: step.name || '',
                desc: step.desc || '',
                note: step.note || '',
                tip: step.tip || '',
                templates: (step.templates || []).map(t => ({
                    tab_label: t.tabLabel || t.tab_label || '',
                    purpose: t.purpose || '',
                    content: t.content || '',
                    shortcut: t.shortcut || '',
                })),
                checklist_items: (step.checklist || []).map(c => ({
                    content: typeof c === 'string' ? c : (c.content || ''),
                })),
            };
            modalOpen('editStepModal');
            this.$nextTick(() => {
                const titleEl = document.querySelector('#editStepModal .modal-header h3');
                if (titleEl) titleEl.textContent = 'Sửa bước: ' + (step.name || '');
            });
        },

        addTemplate() {
            this.editForm.templates.push({ tab_label: '', purpose: '', content: '', shortcut: '' });
        },

        addChecklistItem() {
            this.editForm.checklist_items.push({ content: '' });
        },

        async saveStep() {
            this.saving = true;
            try {
                const stepId = this.editStep.id.toString().replace(/^step/, '');
                const resp = await fetch('/booking-sop/manage/steps/' + stepId, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': getCsrfToken(),
                    },
                    body: JSON.stringify(this.editForm),
                });
                const json = await resp.json();
                if (json.success) {
                    showSuccess('Cập nhật bước thành công');
                    modalClose('editStepModal');
                    location.reload();
                } else {
                    showError(json.message || 'Lỗi không xác định');
                }
            } catch (e) {
                showError('Lỗi kết nối máy chủ');
            } finally {
                this.saving = false;
            }
        },
    }));
}
