package com.yono.messeripos;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
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.bumptech.glide.load.engine.Resource;
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.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textview.MaterialTextView;
import com.yono.messeripos.models.CategoryModels;
import com.yono.messeripos.models.MainViewModels;
import com.yono.messeripos.models.UsersModels;
import com.yono.messeripos.response.DataResponse;
import com.yono.messeripos.utils.Utils;

public class LoginState extends BottomSheetDialogFragment {

    private static final String TAG = "LoginState";
    private static String DEFAULT_LOGIN_NAME = "sign in";
    BottomSheetBehavior sheetBehavior;
    BottomSheetDialog sheetDialog;
    RelativeLayout loginLayout;
    TextInputEditText username, password;
    MaterialButton loginButton;
    ImageView closeBtn;
    Context context;
    MainViewModels mainViewModels;
    SharedPreferences sharedPreferences;
    Utils utils;
    ProgressBar bar;
    View view;
    ProgressDialog dialog;
    MaterialTextView forgot;

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

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

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

        dialog = new ProgressDialog(context);

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

//        bindUI
        loginLayout = view.findViewById(R.id.LoginLayout);
        username = view.findViewById(R.id.ETUsernameLogin);
        password = view.findViewById(R.id.ETPasswordLogin);
        loginButton = view.findViewById(R.id.SignInButtonInLogin);
        closeBtn = view.findViewById(R.id.closeBtnLogin);
        bar = view.findViewById(R.id.progressLogin);
        forgot = view.findViewById(R.id.forgotPwd);

        forgot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, ForgotPasswordActivity.class));
                getActivity().finish();
            }
        });

//        set progress bar gone
        bar.setVisibility(View.GONE);

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

//        utils
        utils = new Utils();

        sheetDialog.setContentView(view);

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

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

//        set max height
        sheetBehavior.setPeekHeight(setHeight);
        loginLayout.setMinimumHeight(setHeight);

//        loginButton on click
        loginButton.setOnClickListener(this::loginAuth);

//        close btn is clicked
        closeBtn.setOnClickListener(view12 -> {
            sheetDialog.dismiss();
        });


        return sheetDialog;
    }

    private void loginAuth(View v) {

        if (TextUtils.isEmpty(username.getText().toString()) &&
                TextUtils.isEmpty(password.getText().toString())){
            username.setError("This field can't empty");
            password.setError("This field can't empty");
        }else if (TextUtils.isEmpty(username.getText().toString()))
        {
            username.setError("This field can't empty");
        }else if (TextUtils.isEmpty(password.getText().toString())){
            password.setError("This field can't empty");
        }else {

            setAllLayoutToFalse();

//            buat checking login
            mainViewModels.checkLogin(new UsersModels(username.getText().toString(),
                    password.getText().toString()))
                    .observe((LifecycleOwner) context, usersModelsDataResponse -> {

                        if (usersModelsDataResponse != null) {

                            switch (usersModelsDataResponse.getMessageData().toLowerCase()) {

                                case "invalid username or password":
                                    setAllLayoutToTrue();
                                    errUserPass();
                                    break;

                                case "please activate your email first":
                                    setAllLayoutToTrue();
                                    activateEmail();

                                default:
                                    break;
                            }

                            if (usersModelsDataResponse.getStatusData()) {

                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putBoolean(SplashScreen.SESSION, true);

                                sheetDialog.dismiss();
                                if(editor.commit()){
                                    startActivity(new Intent(context, MainActivity.class));
                                    getActivity().finish();
                                }

                                setAllLayoutToTrue();

                            }
                        } else {
                            bar.setVisibility(View.VISIBLE);
                            utils.snackBar(v, "Oppss! ログイン中にエラーが発生しました。しばらくしてからもう一度お試しください").show();
                        }

                    });
        }
        loginButton.setText(DEFAULT_LOGIN_NAME);
    }

    private void setAllLayoutToTrue() {
        bar.setVisibility(View.GONE);
        loginButton.setText(DEFAULT_LOGIN_NAME);
        sheetDialog.setCancelable(true);
        username.setEnabled(true);
        password.setEnabled(true);
        loginButton.setEnabled(true);
        closeBtn.setEnabled(true);
    }

    private void setAllLayoutToFalse() {
        bar.setVisibility(View.VISIBLE);
        loginButton.setText("");
        sheetDialog.setCancelable(false);
        username.setEnabled(false);
        password.setEnabled(false);
        loginButton.setEnabled(false);
        closeBtn.setEnabled(false);
    }

    private void activateEmail() {

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

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

    private void errUserPass() {

        utils = new Utils();
        utils.dialog(context, false, "Wrong Username or Password",
                "The username or password is incorrect. Please try again!",
                "Try Again")
                .show();
        utils.setListener(new Utils.DialogListener() {
            @Override
            public void onClickDisimiss(AlertDialog alertDialog) {
                alertDialog.dismiss();
            }

            @Override
            public void onClickLink(AlertDialog alertDialog) {

            }
        });

    }
}
