import BaseComponent from "../BaseComponent";
import { fetchData } from "../../Utils/Fetch";

class Signup {
    init() {
        if (!jQuery('.signup-ui')[0]) {
            return;
        }
        if (jQuery('.signup-ui').data('initializied') !== 'true') {
            new SignupHandler(jQuery('.signup-ui'));
        }
    }
}

class SignupHandler extends BaseComponent {

    _form;
    _submitBtn;
    _signin_google_btn;
    _resend_activation_btn;

    constructor(component_base_ui) {
        super(component_base_ui);
        this._form = this._component_base_ui.find('.oxygenapp-form');
        this._submitBtn = this._form.find(':submit');
        this._signin_google_btn = this._form.find('.signin_google_btn');
        this._resend_activation_btn = this._component_base_ui.find('.resend_activation_btn');

        this.handleRouteChange();
        this._handleEvents();
    }

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

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

    _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');
        this._component_base_ui.find('.turnstile-ui').empty();
    }

    _handleEvents() {
        const _this = this;
        this._signin_google_btn.on('click', function(event) {
            event.preventDefault();
            _this._handleGoogleSignup();
        })

        this._resend_activation_btn.on('click', function(event) {
            event.preventDefault();
            _this._resendActivationLink();
        })

        this._form.on('submit', function(event) {
            event.preventDefault();
            _this._handleSubmit();
            return;
        })
        this.handlePopupClickOutside({
            newHash: '',
        });
    }

    async _resendActivationLink() {
        const email = this._component_base_ui.find('input[name="email"]').val();
        this._component_base_ui.find('.re-send-info').addClass('hidden')
        const result = await fetchData('user-resend-activation', 'POST', {
            email
        });
        if (result?.status === 200) {
            this._component_base_ui.find('.re-send-info').removeClass('hidden');
        } else {
            alert(`${result?.message}`);
        }
    }

    async _handleGoogleSignup() {
        this._submitBtn.attr('disabled', true);
        const result = await fetchData('google-generate-redirect', 'GET');   
        
        if (result?.status === 200) {
            const auth_url = result?.data?.auth_url;
            window.location.href = auth_url;
        } else {
            alert(`${result?.message}`);
        }
        this._submitBtn.attr('disabled', false);
    }

    async _handleSubmit() {

        let token;
        this._submitBtn.attr('disabled', true);
        if (this._shouldAddRecaptcha()) {
            try {
                token = await this.executeRecaptcha('submit');
            } catch (error) {
                alert('Turnstile verification failed!');
                return;
            }
            if (!token) {
                alert('Turnstile verification failed!');
                return;
            }
        }

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

        if (token) {
            payload = { ...payload, token };
        }

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

        const result = await fetchData('user', '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);
    }

}

export default Signup;