class NextButtonManager {
    constructor(tabsManager) {
        this.tabsManager = tabsManager;
        this.nextButtons = new Map();
        this.backButtons = new Map();

        this.tabOrder = ['intro', 'demographics', 'jobs', 'summary', 'preview'];

        this.tabValidators = {
            'intro': () => this.validateIntroTab(),
            'demographics': () => this.validateDemographicsTab(),
            'jobs': () => this.validateJobsTab(),
            'summary': () => this.validateSummaryTab()
        };

        this.errorMessages = {
            'intro': 'Please complete all required fields and select a template before continuing.',
            'demographics': 'Please enter your name before continuing.',
            'jobs': 'Please add at least one job entry before continuing.',
            'summary': 'Please complete all required fields in the summary before continuing.'
        };
    }

    addNextButton(tabName, containerId) {

        if (tabName === 'preview') {
            return;
        }

        if (typeof Button === 'undefined') {
            return;
        }

        const container = document.getElementById(containerId);
        if (!container) {
            setTimeout(() => this.addNextButton(tabName, containerId), 100);
            return;
        }

        const nextButton = new Button({
            containerId: containerId,
            text: 'Next',
            variant: 'primary',
            icon: 'next',
            iconPosition: 'left',
            onClick: (_e, button) => this.handleNextClick(tabName, button)
        });

        this.nextButtons.set(tabName, nextButton);
    }

    addBackButton(containerId) {

        if (typeof Button === 'undefined') {
            return;
        }

        const container = document.getElementById(containerId);
        if (!container) {
            setTimeout(() => this.addBackButton(containerId), 100);
            return;
        }

        const backButton = new Button({
            containerId: containerId,
            text: 'Back',
            variant: 'secondary',
            icon: 'back',
            iconPosition: 'right',
            onClick: (_e, button) => this.handleBackClick(button)
        });

        this.backButtons.set('jobs', backButton);
    }

    handleBackClick(button) {
        const jobsTab = this.tabsManager?.jobsTab;
        if (!jobsTab || !jobsTab.subNav) {
            return;
        }

        const currentSectionIndex = jobsTab.subNav.getCurrentSectionIndex();

        if (currentSectionIndex > 0) {
            const sections = jobsTab.subNav.sections;
            const previousSection = sections[currentSectionIndex - 1];
            jobsTab.subNav.switchSection(previousSection.id);
        }
    }

    handleNextClick(currentTabName, button) {

        button.setLoading(true);
        button.setText('Validating...');

        try {

            if (currentTabName === 'jobs') {
                this.handleJobsTabNavigation(button);
                return;
            }

            const isValid = this.validateCurrentTab(currentTabName);

            if (isValid) {

                this.navigateToNextTab(currentTabName);

                button.setText('Next');
                button.setVariant('primary');
                button.setLoading(false);

            } else {

                button.setText('Please fix errors');
                button.setVariant('error');

                setTimeout(() => {
                    button.setText('Next');
                    button.setVariant('primary');
                    button.setLoading(false);
                }, 2000);
            }

        } catch (error) {
            showError('An error occurred during validation. Please try again.');

            button.setText('Next');
            button.setVariant('primary');
            button.setLoading(false);
        }
    }

    handleJobsTabNavigation(button) {
        const jobsTab = this.tabsManager?.jobsTab;
        if (!jobsTab || !jobsTab.subNav) {
            button.setText('Next');
            button.setVariant('primary');
            button.setLoading(false);
            return;
        }

        const sections = jobsTab.subNav.sections;
        const currentSectionId = jobsTab.subNav.getActiveSection();
        const currentSectionIndex = sections.findIndex(s => s.id === currentSectionId);

        const isValid = this.validateJobsSection(currentSectionId);

        if (isValid) {

            if (currentSectionIndex === sections.length - 1) {

                this.navigateToNextTab('jobs');
            } else {

                const nextSection = sections[currentSectionIndex + 1];
                jobsTab.subNav.switchSection(nextSection.id);
            }

            button.setText('Next');
            button.setVariant('primary');
            button.setLoading(false);

        } else {

            button.setText('Please fix errors');
            button.setVariant('error');

            setTimeout(() => {
                button.setText('Next');
                button.setVariant('primary');
                button.setLoading(false);
            }, 2000);
        }
    }

    validateJobsSection(sectionId) {
        const jobsTab = this.tabsManager?.jobsTab;
        if (!jobsTab) return false;

        try {

            const sectionValidators = {
                'physical-demands': () => jobsTab.physicalDemands.validate(),
                'mobility-demands': () => jobsTab.mobilityDemands.validate(),
                'cognitive-sensory': () => jobsTab.cognitiveSensoryDemands.validate(),
                'environmental': () => jobsTab.environmentalDemands.validate(),
                'lifting-pushing-pulling': () => jobsTab.liftingPushingPulling.validate(),
                'classification': () => jobsTab.classificationOfWork.validate()
            };

            const validator = sectionValidators[sectionId];
            if (!validator) {
                return true;
            }

            const isValid = validator();

            if (!isValid) {

                let errorMessage = 'Please complete all required fields in this section before continuing.';

                if (sectionId === 'classification') {
                    const errors = jobsTab.classificationOfWork.demandLevelSelector?.getValidationErrors();
                    if (errors && errors['demand-level']) {
                        errorMessage = errors['demand-level'];
                    }
                }

                showError(errorMessage, { duration: 6 });
            }

            return isValid;

        } catch (error) {
            showError('Validation failed. Please check your inputs and try again.');
            return false;
        }
    }

    validateCurrentTab(tabName) {
        const validator = this.tabValidators[tabName];

        if (!validator) {
            return true;
        }

        try {
            const isValid = validator();

            if (!isValid) {

                if (tabName !== 'summary') {
                    const errorMessage = this.errorMessages[tabName] || 'Please complete all required fields.';
                    showError(errorMessage, { duration: 6 });
                }
            }

            return isValid;

        } catch (error) {
            showError('Validation failed. Please check your inputs and try again.');
            return false;
        }
    }

    navigateToNextTab(currentTabName) {
        const currentIndex = this.tabOrder.indexOf(currentTabName);

        if (currentIndex === -1) {
            return;
        }

        const nextIndex = currentIndex + 1;

        if (nextIndex >= this.tabOrder.length) {
            return;
        }

        const nextTabName = this.tabOrder[nextIndex];

        if (this.tabsManager && this.tabsManager.switchToTab) {
            this.tabsManager.switchToTab(nextTabName);
        }
    }

    validateIntroTab() {
        if (!this.tabsManager || !this.tabsManager.introTab) {
            return false;
        }

        return this.tabsManager.introTab.validate();
    }

    validateDemographicsTab() {
        if (!this.tabsManager || !this.tabsManager.demographicsTab) {
            return false;
        }

        return this.tabsManager.demographicsTab.validate();
    }

    validateJobsTab() {
        if (!this.tabsManager || !this.tabsManager.jobsTab) {
            return false;
        }

        return this.tabsManager.jobsTab.validate();
    }

    validateSummaryTab() {
        if (!this.tabsManager || !this.tabsManager.summaryTab) {
            return false;
        }

        return this.tabsManager.summaryTab.validate();
    }

    getNextButton(tabName) {
        return this.nextButtons.get(tabName) || null;
    }

    removeNextButton(tabName) {
        const button = this.nextButtons.get(tabName);
        if (button) {
            button.destroy();
            this.nextButtons.delete(tabName);
        }
    }

    removeAllNextButtons() {
        for (const [_tabName, button] of this.nextButtons) {
            button.destroy();
        }
        this.nextButtons.clear();
    }

    updateNextButton(tabName, options = {}) {
        const button = this.nextButtons.get(tabName);
        if (!button) {
            return;
        }

        if (options.text) button.setText(options.text);
        if (options.variant) button.setVariant(options.variant);
        if (options.disabled !== undefined) button.setDisabled(options.disabled);
        if (options.loading !== undefined) button.setLoading(options.loading);
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = NextButtonManager;
}