package org.stepic.droid.ui.dialogs;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;

import org.jetbrains.annotations.NotNull;
import org.stepic.droid.R;
import org.stepic.droid.base.App;
import org.stepic.droid.di.qualifiers.BackgroundScheduler;
import org.stepic.droid.di.qualifiers.MainScheduler;
import org.stepic.droid.util.ProgressHelper;
import org.stepik.android.domain.auth.repository.AuthRepository;

import javax.inject.Inject;

import butterknife.BindString;
import butterknife.ButterKnife;
import io.reactivex.Scheduler;
import io.reactivex.disposables.CompositeDisposable;
import kotlin.text.StringsKt;
import ru.nobird.android.view.base.ui.extension.ViewExtensionsKt;

public class RemindPasswordDialogFragment extends DialogFragment {

    private static final String ERROR_TEXT_KEY = "Error_Text_Key";

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Inject
    AuthRepository authRepository;

    @Inject
    @MainScheduler
    Scheduler mainScheduler;

    @Inject
    @BackgroundScheduler
    Scheduler backgroundScheduler;

    public static RemindPasswordDialogFragment newInstance() {
        return new RemindPasswordDialogFragment();
    }

    private TextInputLayout emailTextWrapper;
    private Dialog progressLogin;
    private View rootView;

    @BindString(R.string.email_wrong)
    String emailWrong;


    @NotNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        App.Companion.component().inject(this);

        @SuppressLint("InflateParams") //it is dialog and it shoud not have any parent
        View v = LayoutInflater.from(requireContext()).inflate(R.layout.view_remind_password, null, false);
        emailTextWrapper = v.findViewById(R.id.emailViewWrapper);
        rootView = v.findViewById(R.id.root_view_dialog);
        rootView.requestFocus();

        progressLogin = new MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.loading)
                .setView(R.layout.dialog_progress)
                .setCancelable(false)
                .create();

        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext());
        builder.setTitle(R.string.remind_password)
                .setView(v)
                .setPositiveButton(R.string.send, (dialog, which) -> {})
                .setNegativeButton(R.string.cancel, null);
        final AlertDialog alertDialog = builder.create();
        alertDialog.setOnShowListener(dialog -> {
            Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            bindEmailChangeToButton(b);
            b.setOnClickListener(view -> sendEmail(alertDialog));
        });

        if (emailTextWrapper.getEditText() != null) {
            emailTextWrapper.getEditText().setOnEditorActionListener((v1, actionId, event) -> {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendEmail(alertDialog);
                    handled = true;
                }
                return handled;
            });

            emailTextWrapper.getEditText().setOnFocusChangeListener((v12, hasFocus) -> {
                if (hasFocus) {
                    hideError(emailTextWrapper);
                }
            });
        }

        ButterKnife.bind(this, alertDialog);

        if (savedInstanceState != null) {
            String errorText = savedInstanceState.getString(ERROR_TEXT_KEY);
            if (errorText != null) {
                showError(emailTextWrapper, errorText);
            }
        }

        return alertDialog;
    }

    private void sendEmail(final AlertDialog alertDialog) {
        ProgressHelper.activate(progressLogin);

        final EditText editText = emailTextWrapper.getEditText();
        if (editText != null) {
            ViewExtensionsKt.hideKeyboard(editText);
        }
        String email;
        try {
            email = emailTextWrapper.getEditText().getText().toString().trim();
        } catch (NullPointerException e) {
            ProgressHelper.dismiss(progressLogin);
            return;
        }
        compositeDisposable.add(authRepository.remindPassword(email)
                .observeOn(mainScheduler)
                .subscribeOn(backgroundScheduler)
                .subscribe((response) -> {
                    ProgressHelper.dismiss(progressLogin);
                    okhttp3.Response rawResponse = response.raw();
                    if (rawResponse.priorResponse() != null && rawResponse.priorResponse().code() == 302) {
                        alertDialog.dismiss();
                        Toast.makeText(getContext(), R.string.email_sent, Toast.LENGTH_SHORT).show();
                    } else if (response.code() == 200) {
                        if (rootView != null)
                            rootView.requestFocus();
                        showError(emailTextWrapper, emailWrong);
                    } else {
                        final Context context = getContext();
                        if (context != null) {
                            Toast.makeText(context, R.string.connectionProblems, Toast.LENGTH_SHORT).show();
                        }
                    }
                }, (error) -> {
                    ProgressHelper.dismiss(progressLogin);

                    final Context context = getContext();
                    if (context != null) {
                        Toast.makeText(context, R.string.connectionProblems, Toast.LENGTH_SHORT).show();
                    }
                })
        );
    }

    private void bindEmailChangeToButton(final Button button) {
        EditText email = emailTextWrapper.getEditText();
        if (email != null) {
            setSubmitButtonState(button, email.getText().toString());
            email.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    setSubmitButtonState(button, s.toString());
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void afterTextChanged(Editable s) {}
            });
        }
    }

    private void setSubmitButtonState(final Button button, String text) {
        button.setEnabled(!StringsKt.isBlank(text));
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (emailTextWrapper != null && emailTextWrapper.getError() != null)
            outState.putString(ERROR_TEXT_KEY, emailTextWrapper.getError().toString());

    }

    @Override
    public void onStop() {
        compositeDisposable.clear();
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        if (emailTextWrapper != null && emailTextWrapper.getEditText() != null) {
            emailTextWrapper.getEditText().setOnFocusChangeListener(null);
            emailTextWrapper.getEditText().setOnEditorActionListener(null);
        }
        super.onDestroyView();
    }

    private void hideError(TextInputLayout textInputLayout) {
        if (textInputLayout != null) {
            textInputLayout.setError("");
            textInputLayout.setErrorEnabled(false);
        }
    }

    private void showError(TextInputLayout textInputLayout, String errorText) {
        if (textInputLayout != null) {
            textInputLayout.setErrorEnabled(true);
            textInputLayout.setError(errorText);
        }
    }
}

@@ -998,71 +998,8 @@
 t;%0A%0A
-import butterknife.BindString;%0Aimport butterknife.ButterKnife;%0A
 impo
@@ -1021,24 +1021,24 @@
 .Scheduler;%0A
+
 import io.re
@@ -1808,71 +1808,8 @@
 w;%0A%0A
-    @BindString(R.string.email_wrong)%0A    String emailWrong;%0A%0A%0A
     
@@ -3756,54 +3756,8 @@
  %7D%0A%0A
-        ButterKnife.bind(this, alertDialog);%0A%0A
     
@@ -5333,19 +5333,40 @@
 er, 
+getString(R.string.
 email
-W
+_w
 rong)
+)
 ;%0A  

remove butterknife from RemindDialogFragment