package co.pixelbeard.theanfieldwrap.forgotPassword;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;

import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.forgotPassword.fpAuth.ForgotPasswordAuthFragment;
import co.pixelbeard.theanfieldwrap.forgotPassword.fpEmail.ForgotPasswordEmailFragment;
import co.pixelbeard.theanfieldwrap.forgotPassword.fpNewPassword.ForgotPasswordNewPasswordFragment;
import co.pixelbeard.theanfieldwrap.utils.AnimUtils;
import co.pixelbeard.theanfieldwrap.utils.BaseActivity;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.DialogUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.FragmentUtils;
import io.realm.Realm;

public class ForgotPasswordActivity extends BaseActivity implements ForgotPasswordFragmentListener, ForgotPasswordContract.View {

    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.txt_forgot_password_step)
    TextView txtForgotPasswordStep;
    @BindView(R.id.btn_next)
    CircularProgressButton btnNext;
    @BindView(R.id.btn_resend_code)
    Button btnResendCode;
    @BindView(R.id.fl_frag_container)
    FrameLayout flFragContainer;

    @BindView(R.id.ll_no_internet_header)
    LinearLayout llNoInternetHeader;
    @BindView(R.id.txt_no_internet_header)
    TextView txtNoInternetHeader;

    private FragmentManager mFragMan;
    private ForgotPasswordContract.Presenter mPresenter;

    private String mEmail, mConfirmationCode, mNewPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);

        ButterKnife.bind(this);

        new ForgotPasswordPresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));

        setButtonFont();
        setButtonClickListener();

        setTextViewFont();

        setupFragManager();

        setForgotPasswordEmailFrag();
    }

    private void setButtonFont() {
        btnNext.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        btnResendCode.setTypeface(FontUtils.getInstance().getDinCondensedBold());
    }

    private void setButtonClickListener() {
        llBack.setOnClickListener(v -> {
            onBackPressed();
        });

        btnNext.setOnClickListener(v -> {
            mPresenter.nextClicked(mFragMan);
        });

        btnResendCode.setOnClickListener(v -> {
            mPresenter.requestPasswordReset(mEmail, true);
        });

    }

    private void setTextViewFont() {
        txtForgotPasswordStep.setTypeface(FontUtils.getInstance().getDinCondensedBold());
    }

    private void setupFragManager() {

        mFragMan = getSupportFragmentManager();

        mFragMan.addOnBackStackChangedListener(() -> {

            if (mFragMan.getBackStackEntryCount() > 0) {
                String tag = mFragMan.getBackStackEntryAt(mFragMan.getBackStackEntryCount() - 1).getName();
                if (tag != null) {
                    switch (tag) {
                        case "FORGOT_PASS_EMAIL":
                            txtForgotPasswordStep.setText(getString(R.string.sign_up_step_1));
                            btnResendCode.setVisibility(View.INVISIBLE);
                            break;
                        case "FORGOT_PASS_AUTH":
                            txtForgotPasswordStep.setText(getString(R.string.sign_up_step_2));
                            btnResendCode.setVisibility(View.VISIBLE);
                            break;
                        case "FORGOT_PASS_NEW_PASS":
                            txtForgotPasswordStep.setText(getString(R.string.sign_up_step_3));
                            btnResendCode.setVisibility(View.INVISIBLE);
                            break;
                    }
                }
            }

            if (mFragMan.getBackStackEntryCount() == 2) {
                btnResendCode.setVisibility(View.VISIBLE);
                btnResendCode.setEnabled(true);
            } else {
                btnResendCode.setVisibility(View.INVISIBLE);
                btnResendCode.setEnabled(false);
            }
        });
    }

    @Override
    public void setForgotPasswordEmailFrag() {
        FragmentUtils.doReplaceFragmentTransaction(mFragMan, flFragContainer.getId(), ForgotPasswordEmailFragment.newInstance(), "FORGOT_PASS_EMAIL", true);

    }

    @Override
    public void setForgotPasswordAuthFrag() {
        FragmentUtils.doReplaceFragmentTransaction(mFragMan, flFragContainer.getId(), ForgotPasswordAuthFragment.newInstance(), "FORGOT_PASS_AUTH", true);
    }

    @Override
    public void setForgotPasswordNewPasswordFrag() {
        FragmentUtils.doReplaceFragmentTransaction(mFragMan, flFragContainer.getId(), ForgotPasswordNewPasswordFragment.newInstance(), "FORGOT_PASS_NEW_PASS", true);
    }

    @Override
    public void finishForgotPasswordActivity() {
        finish();
        overridePendingTransition(R.anim.slide_in_from_left_fast, R.anim.slide_out_right);
    }

    @Override
    public void requestPasswordReset() {
        mPresenter.requestPasswordReset(mEmail, false);
    }

    @Override
    public void resetPassword() {
        mPresenter.resetPassword(mEmail, mConfirmationCode, mNewPassword);
    }

    @Override
    public void setEmail(String email) {
        this.mEmail = email;
    }

    @Override
    public void setConfirmationCode(String code) {
        this.mConfirmationCode = code;
    }

    @Override
    public void setNewPassword(String password) {
        this.mNewPassword = password;
    }

    @Override
    public void enableButton() {
        btnNext.setAlpha(1.0f);
    }

    @Override
    public void disableButton() {
        btnNext.setAlpha(0.2f);
    }

    @Override
    public void setPresenter(ForgotPasswordContract.Presenter presenter) {
        if (presenter != null) {
            this.mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        onBackPressed();
    }

    @Override
    public void showLoader(String text) {
        if (!isFinishing())
            btnNext.startMorphAnimation();
    }

    @Override
    public void hideLoader() {
        if (!isFinishing())
            btnNext.revertAnimation(() -> null);
    }

    @Override
    public void showSingleButtonDialog(String title, String body, DialogInterface.OnDismissListener listener) {
        if (!isFinishing()) {
            DialogUtils.showSingleButtonDialog(title, body, this, listener);
        }
    }

    @Override
    public void showResentToast() {
        Toast.makeText(this, "Password reset resent", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onUnknownError(String error) {
        showSingleButtonDialog(getString(R.string.error), error, null);
    }

    @Override
    public void onTimeout() {
        showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body), null);
    }

    @Override
    public void onNetworkError() {
        showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body), null);
    }

    @Override
    public void onConnectionError() {
        showNoInternetHeader();
    }

    public void showNoInternetHeader() {
        AnimUtils.slideInTop(llNoInternetHeader, 300, new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llNoInternetHeader.setVisibility(View.VISIBLE);
                hideNoInternetHeader();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        }, new AccelerateInterpolator());
    }

    public void hideNoInternetHeader() {
        new Handler().postDelayed(() -> {
            AnimUtils.slideOutTop(llNoInternetHeader, 300, new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    llNoInternetHeader.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }, 3000);
    }

    @Override
    public void logoutUser() {
        //Not needed
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(this);
    }

    @Override
    public void onBackPressed() {
        if (mFragMan.getBackStackEntryCount() == 1) {
            finish();
            overridePendingTransition(R.anim.slide_in_from_left_fast, R.anim.slide_out_right);
        } else {
            mFragMan.popBackStack();
        }
    }
}
