
import BaseComponent from "../BaseComponent";
import EventBus, { Events, Event} from "../../Events/EventBus";
import Utils from "../../Utils/Utils";
import HashRouter from "../../Router/HashRouter";
import { fetchData } from "../../Utils/Fetch";

class ResetPassword {
    init() {
        if (!jQuery('.resetpass-ui')[0]) {
            return;
        }
        if (jQuery('.resetpass-ui').data('initializied') !== 'true') {
            new ResetPasswordHandler(jQuery('.resetpass-ui'))
        }
    }
}

class ResetPasswordHandler extends BaseComponent {
    
    _form;
    _submitBtn;

    constructor(component_base_ui) {
        super(component_base_ui);
        this._form = this._component_base_ui.find('.oxygenapp-form');
        this._submitBtn = this._form.find(':submit');
        this.handleRouteChange();
        this._handleForm();
        this.handlePopupClickOutside({
            newHash: '',
        });
    }

    _handleForm() {
        const _this = this;
        this._form.on('submit', function(event) {
            event.preventDefault();
            _this._handleSubmit();
            return;
        })
    }

    async _handleSubmit() {

        let payload = {
            code: this._component_base_ui.find('input[name="code"]').val(),
            password: this._component_base_ui.find('input[name="password"]').val(),
        }

        this._submitBtn.attr('disabled', true);
        this.hideFormErrorOnLoad();

        const result = await fetchData('reset-password', 'POST', payload);
        if (result?.status === 200) {
            this.showFormSuccess();
            this.hideForm();
        } else {
            this._component_base_ui.find('.form-error').html(result?.message);
            this.showFormError();
        }
        this._submitBtn.attr('disabled', false);
    }

    onRouteChange(payload) {
        const { key } = payload;
        if (key === 'reset_password') {
            this._showPopup(payload);
        } else {
            this._closePopup();
        }
    }

    _showPopup(payload) {
        document.title = payload?.data?.page_title ?? '';
        this._handleResetView();
        this.checkRecaptcha();
        this.show();
        this.fadeIn();
        this.hideFormErrorOnLoad();
        this.hideFormSuccessOnLoad();
        this._populateCode();
    }

    _closePopup() {
        this.hide();
        this.fadeOut();
    }

    _handleResetView() {
        this._component_base_ui.find('.form-success').addClass('hidden');
        this._component_base_ui.find('.form-error').addClass('hidden');
        this._form.removeClass('hidden');
    }

    _populateCode() {
        const resetCode = HashRouter.getQueryParamFromHash('code');
        if (resetCode) {
            this._component_base_ui.find('input[name="code"]').val(resetCode);
        }
    }
}

export default ResetPassword;