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

class ForgotPassword {
    init() {
        if (!jQuery('.forgotpass-ui')[0]) {
            return;
        }
        if (jQuery('.forgotpass-ui').data('initializied') !== 'true') {
            new ForgotPasswordHandler(jQuery('.forgotpass-ui'))
        }
    }
}

class ForgotPasswordHandler 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 = {
            email: this._component_base_ui.find('input[name="email"]').val(),
        }

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

        const result = await fetchData('reset-password-request', '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 === 'forgot_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();
    }

    _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');
    }
}

export default ForgotPassword;