package com.yono.messeripos;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.yono.messeripos.api.client.Client;
import com.yono.messeripos.api.service.UsersService;
import com.yono.messeripos.models.MainViewModels;
import com.yono.messeripos.models.UsersModels;
import com.yono.messeripos.response.DataResponse;
import com.yono.messeripos.utils.Utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterState extends BottomSheetDialogFragment {

    private static final String TAG = "RegisterState";
    private static String DEFAULT_REGISTER = "CREATE ACCOUNT";
    BottomSheetBehavior sheetBehavior2;
    BottomSheetDialog sheetDialog2;
    RelativeLayout registerLayout;
    TextInputEditText username, email, password, repassword;
    MaterialButton registerButton;
    ImageView closeBtn;
    Context context;
    MainViewModels mainViewModels;
    SharedPreferences sharedPreferences;
    ProgressBar pbReg;
    Utils utils;

    public RegisterState(Context context, MainViewModels mainViewModels) {
        this.context = context;
        this.mainViewModels = mainViewModels;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        sheetDialog2 = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

//        inflating layout
        View view = View.inflate(getContext(), R.layout.register_form, null);

//        bindUI
        registerLayout = view.findViewById(R.id.RegisterLayout);
        username = view.findViewById(R.id.ETUsernameReg);
        email = view.findViewById(R.id.ETEmailReg);
        password = view.findViewById(R.id.ETPasswordReg);
        repassword = view.findViewById(R.id.ETRePasswordReg);
        registerButton = view.findViewById(R.id.MBRegister);
        closeBtn = view.findViewById(R.id.ivclose);
        pbReg = view.findViewById(R.id.progressReg);

//        create session
        sharedPreferences = context.getSharedPreferences(SplashScreen.MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);

//        utils
        utils = new Utils();

        sheetDialog2.setContentView(view);
        pbReg.setVisibility(View.GONE);

        sheetBehavior2 = BottomSheetBehavior.from((View) (view.getParent()));

//        get Window size
        int setHeight = utils.getWindowHeight() - (utils.getWindowHeight() * 5) / 100;

//        set max height
        sheetBehavior2.setPeekHeight(setHeight);
        registerLayout.setMinimumHeight(setHeight);

        Log.d(TAG, "onCreateDialog: " + sheetBehavior2.getState());

        email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(username.getText().toString()) &&
                        TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(password.getText().toString()) && TextUtils.isEmpty(repassword.getText().toString())) {
                    username.setError("This field can't empty");
                    email.setError("This field can't empty");
                    password.setError("This field can't empty");
                    repassword.setError("This field can't empty");
                } else if (TextUtils.isEmpty(username.getText().toString())) {
                    username.setError("This field can't empty");
                } else if (TextUtils.isEmpty(email.getText().toString())) {
                    email.setError("This field can't empty");
                } else if (TextUtils.isEmpty(password.getText().toString())) {
                    password.setError("This field can't empty");
                } else if (TextUtils.isEmpty(repassword.getText().toString())) {
                    repassword.setError("This field can't empty");
                } else if (!utils.isValidEmail(charSequence.toString())) {
                    email.setError("Please enter the correct email format");
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //same data password
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (TextUtils.isEmpty(username.getText().toString()) &&
                        TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(password.getText().toString()) && TextUtils.isEmpty(repassword.getText().toString())) {
                    username.setError("This field can't empty");
                    email.setError("This field can't empty");
                    password.setError("This field can't empty");
                    repassword.setError("This field can't empty");
                } else if (!utils.isValidPassword(charSequence.toString())) {
                    password.setError("Password Must Be 8 Character");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        final LifecycleOwner lifecycleOwner = this;
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mainViewModels.postRegis(
                        new UsersModels(username.getText().toString(),
                                email.getText().toString(), password.getText().toString(),
                                repassword.getText().toString())).observe(lifecycleOwner, new Observer<DataResponse<UsersModels>>() {
                    @Override
                    public void onChanged(DataResponse<UsersModels> usersModelsDataResponse) {
                        /**
                         * RESPONSE AGAR ADA PROGRESS DIALOGNYA
                         * KETIKA RESPONNYA SUCCESS MAKA PROGRESS DIalog diSMISS
                         * DAN ALERT ACTIVATE MUNCUL
                         * */
                        setAllLayoutToFalse();
                        if (usersModelsDataResponse != null) {
                            final View customLayout = getLayoutInflater()
                                    .inflate(R.layout.alert_dialog, null);

                            activateEmail(customLayout);
                            setAllLayoutToTrue();
                        }
                    }
                });
            }
        });


//        close btn is clicked
        closeBtn.setOnClickListener(view12 -> {
            Log.d(TAG, "onCreateDialog: " + sheetBehavior2.getState());
            sheetDialog2.dismiss();
        });

        return sheetDialog2;
    }

<<<<<<< HEAD
    private void activateEmail() {
=======

    private void
    setAllLayoutToTrue() {
        pbReg.setVisibility(View.GONE);
        registerButton.setText(DEFAULT_REGISTER);
        sheetDialog2.setCancelable(true);
        username.setEnabled(true);
        email.setEnabled(true);
        password.setEnabled(true);
        repassword.setEnabled(true);
        registerButton.setEnabled(true);
        closeBtn.setEnabled(true);
    }

    private void setAllLayoutToFalse() {
        pbReg.setVisibility(View.VISIBLE);
        registerButton.setText("");
        sheetDialog2.setCancelable(false);
        username.setEnabled(false);
        password.setEnabled(false);
        registerButton.setEnabled(false);
        closeBtn.setEnabled(false);
    }


    private void activateEmail(View customLayout) {
>>>>>>> dev

        utils = new Utils();
        utils.dialog(context, false, "Please Verifiy Email",
                "Please verify your email before login",
                "close", "verify")
                .show();
        utils.setListener(new Utils.DialogListener() {
            @Override
            public void onClickDisimiss(AlertDialog alertDialog) {

                alertDialog.dismiss();
                sheetDialog2.dismiss();

            }

            @Override
            public void onClickLink(AlertDialog alertDialog) {
                Intent pm = getActivity().getPackageManager().getLaunchIntentForPackage("com.google.android.gm");
                if (pm != null) {
                    startActivity(pm);
                    getActivity().finish();
                }
            }
        });
    }
}
