package com.cygnusa.hyperm;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.pinview.PinView;
import com.cygnusa.hyperm.tooltip.Tooltip;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.OtpResponse;
import com.cygnusa.hyperm.wrappers.SignupResponse;
import com.cygnusa.hyperm.wrappers.UserResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


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


public class SignUpActivity extends AppCompatActivity {
  public OtpResponse errorResponse = new OtpResponse();
  public SignupResponse signup = new SignupResponse();
  public UserResponse user = new UserResponse();
  public int counter;
  ApiService restService;
  TransparentProgressDialog progressDialog;
  AlertDialog.Builder alertDialogBuilder;
  AlertDialog alertDialog;
  PinView pinview;
  private EditText mEditUserName;

  public static void hideSoftKeyboard(Activity activity) {
    try {
      InputMethodManager inputMethodManager =
              (InputMethodManager) activity.getSystemService(
                      Activity.INPUT_METHOD_SERVICE);
      inputMethodManager.hideSoftInputFromWindow(
              activity.getCurrentFocus().getWindowToken(), 0);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.acitivity_signup);
    setupWindowAnimations();
    setupUI(findViewById(R.id.bgLayout));
    restService = ((MainApplication) getApplication()).getClient();
    mEditUserName = findViewById(R.id.username_signup);
    findViewById(R.id.sign_up_button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        signUp();
      }
    });
    TextView textView = (TextView) findViewById(R.id.alreadyRegistered);
    SpannableString content = new SpannableString("Login");
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textView.setText(content);

    findViewById(R.id.alreadyRegistered).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        finish();
        overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
      }
    });

    findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        String header = "If you are dealer staff enter the SMPIN for registering and logging into the system\n" +
                "\nIf you are HYPER-M staff enter your Employee ID for registering and logging into the system";
        View mView = LayoutInflater.from(SignUpActivity.this).inflate(R.layout.login_tooltip_text, null);
        TextView text = mView.findViewById(R.id.text11);
        text.setText(header);
        Tooltip.TooltipView tooltip = Tooltip.make(SignUpActivity.this,
                new Tooltip.Builder(101)
                        .anchor(view, Tooltip.Gravity.TOP)
                        .closePolicy(new Tooltip.ClosePolicy()
                                .insidePolicy(true, false)
                                .outsidePolicy(true, false), 0)
                        .activateDelay(800)
                        .withStyleId(R.style.ToolTipLayoutCustomStyle)
                        .showDelay(300)
                        .text("")
                        .setBgColor(getResources().getColor(R.color.bg_color))
                        .view(mView)
                        .maxWidth(300)
                        .withArrow(true)
                        .build()
        );
        tooltip.setTextColor(Color.YELLOW);
        tooltip.show();
      }
    });

    checkPermission();

  }
  private void checkPermission() {
    if (Build.VERSION.SDK_INT >= 23) {
      ArrayList<String> listPermissionsNeeded = new ArrayList<>();
      if (checkSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
        listPermissionsNeeded
                .add(android.Manifest.permission.READ_SMS);
        listPermissionsNeeded
                .add(android.Manifest.permission.READ_SMS);
      }

      if (!listPermissionsNeeded.isEmpty())
        ActivityCompat.requestPermissions(this, listPermissionsNeeded
                .toArray(new String[listPermissionsNeeded.size()]), 1);

    }
  }

  private void signUp() {
    String userName = mEditUserName.getText().toString().trim();
    boolean cancel = false;
    View focusView = null;
    if (TextUtils.isEmpty(userName)) {
      GlobalData.showToast(getBaseContext(), "Please enter the SMPIN/Employee ID", Toast.LENGTH_SHORT).show();
      focusView = mEditUserName;
      cancel = true;
    }

    if (cancel) {
      focusView.requestFocus();
    } else {
      if (new UtilService().isNetworkAvailable(SignUpActivity.this)) {
        progressDialog = new TransparentProgressDialog(SignUpActivity.this);
        progressDialog.show();

        try {
          HashMap<String, String> map = new HashMap<>();
          map.put("username", userName);

          restService.SignUp(map).enqueue(new Callback<SignupResponse>() {
            @Override
            public void onResponse(Call<SignupResponse> call, Response<SignupResponse> response) {
              signup = response.body();
              if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
              }
              if (signup != null && signup.getStatus() == 200) {
                showPopup(signup.getData().getMobile());
              } else if (signup != null) {
                GlobalData.showToast(getBaseContext(), signup.getMessage(), Toast.LENGTH_SHORT).show();
              } else if (response.errorBody() != null) {
                Gson gson = new Gson();
                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
              }
            }

            @Override
            public void onFailure(Call<SignupResponse> call, Throwable t) {
              if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
              }
              GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
          });

        } catch (Exception e) {
          e.printStackTrace();
        }
      } else {
        GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
      }
    }
  }

  public void sentOtp() {
    if (new UtilService().isNetworkAvailable(SignUpActivity.this)) {
      progressDialog = new TransparentProgressDialog(SignUpActivity.this);
      progressDialog.show();

      try {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", signup.getData().getUsername());
        map.put("device_type","android");
        restService.sentOtp(map).enqueue(new Callback<OtpResponse>() {
          @Override
          public void onResponse(Call<OtpResponse> call, Response<OtpResponse> response) {
            errorResponse = response.body();

            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }
            if (errorResponse != null && errorResponse.getStatus() == 200) {
              showOtpPopUp(signup.getData().getMobile(), errorResponse.getData().getOtp_expiry());
            } else if (errorResponse != null) {
              GlobalData.showToast(getBaseContext(), errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
            } else if (response.errorBody() != null) {
              Gson gson = new Gson();
              ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
              GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
            }
          }

          @Override
          public void onFailure(Call<OtpResponse> call, Throwable t) {
            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }

            GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
          }
        });

      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
    }
  }

  public void reSentOtp() {
    if (new UtilService().isNetworkAvailable(SignUpActivity.this)) {
      progressDialog = new TransparentProgressDialog(SignUpActivity.this);
      progressDialog.show();
      try {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", signup.getData().getUsername());

        restService.sentOtp(map).enqueue(new Callback<OtpResponse>() {
          @Override
          public void onResponse(Call<OtpResponse> call, Response<OtpResponse> response) {
            errorResponse = response.body();
            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }
            if (errorResponse != null && errorResponse.getStatus() == 200) {
              showOtpPopUp(signup.getData().getMobile(), errorResponse.getData().getOtp_expiry());
            } else if (errorResponse != null) {
              GlobalData.showToast(getBaseContext(), errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
            } else if (response.errorBody() != null) {
              Gson gson = new Gson();
              ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
              GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
            }


          }

          @Override
          public void onFailure(Call<OtpResponse> call, Throwable t) {
            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }
            GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
          }
        });

      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
    }

  }


  private void showPopup(final String mobileNo) {

    if (mobileNo == null || mobileNo.trim().isEmpty()) {
      GlobalData.showToast(getBaseContext(), "Invalid Mobile Number", Toast.LENGTH_SHORT).show();
      return;
    }


    View view = LayoutInflater.from(SignUpActivity.this).inflate(
            R.layout.signup_alert_window, null);


    view.findViewById(R.id.btn_yes).setOnClickListener(
            new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                alertDialog.dismiss();

                sentOtp();
              }
            });
    view.findViewById(R.id.btn_no).setOnClickListener(
            new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                alertDialog.dismiss();
                showInstructions();
              }
            });

    String strLast3digit = mobileNo.substring(mobileNo.length() - 3);
    String strFirst2digit = mobileNo.substring(0, 2);
    TextView mobileNumTextView = view.findViewById(R.id.mobileNo);
    String alterStr = new StringBuilder(mobileNo).replace(2, 7, "XXXXX").toString();
    mobileNumTextView.setText(alterStr);


    alertDialogBuilder = new AlertDialog.Builder(SignUpActivity.this);
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setView(view);
    alertDialog = alertDialogBuilder.create();
    alertDialog.show();
  }

  private void showInstructions() {
    View view = LayoutInflater.from(SignUpActivity.this).inflate(
            R.layout.signup_instruction_popup, null);

    view.findViewById(R.id.btn_ok).setOnClickListener(
            new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                alertDialog.dismiss();

              }
            });

    alertDialogBuilder = new AlertDialog.Builder(SignUpActivity.this);
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setView(view);
    alertDialog = alertDialogBuilder.create();
    alertDialog.show();
  }

  private void showOtpPopUp(String mobileNo, String otpexpirytime) {
    if (mobileNo == null || mobileNo.trim().isEmpty()) {
      GlobalData.showToast(getBaseContext(), "Invalid Mobile Number", Toast.LENGTH_SHORT).show();
      return;
    }
    View view = LayoutInflater.from(SignUpActivity.this).inflate(
            R.layout.otp_popup, null);

    pinview = (PinView) view.findViewById(R.id.pinView);


    TextView mobileNumTextView = view.findViewById(R.id.mobileNo);
    final TextView resentOtpTxt = view.findViewById(R.id.resentOtp);
    resentOtpTxt.setEnabled(false);
    resentOtpTxt.setAlpha(0.5f);

    final TextView count_time = view.findViewById(R.id.count_time);
    view.findViewById(R.id.btn_cancel).setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                alertDialog.dismiss();
              }
            });
    resentOtpTxt.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                alertDialog.dismiss();
                reSentOtp();
              }
            });
    view.findViewById(R.id.btn_submit).setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                if (pinview.getText().toString().equalsIgnoreCase("")) {
                  GlobalData.showToast(getBaseContext(), "Please enter Valid OTP", Toast.LENGTH_SHORT).show();
                  return;
                }
                otpValidation(pinview.getText().toString());

              }
            });

    int millsec = Integer.parseInt(otpexpirytime) * 60 * 1000;
    new android.os.CountDownTimer(millsec, 1000) {
      public void onTick(long millisUntilFinished) {

        String formattedTime = String.format("%02d:%02d Sec",
                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % TimeUnit.HOURS.toMinutes(1),
                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % TimeUnit.MINUTES.toSeconds(1));
        count_time.setText(formattedTime);
        counter++;
      }

      public void onFinish() {
        count_time.setText("00:00");
        resentOtpTxt.setEnabled(true);
        resentOtpTxt.setAlpha(1f);
      }
    }.start();

    Paint p = new Paint();
    p.setColor(getResources().getColor(R.color.btn_bg_color));
    resentOtpTxt.setPaintFlags(resentOtpTxt.getPaintFlags() | p.UNDERLINE_TEXT_FLAG);
    String alterStr = new StringBuilder(mobileNo).replace(2, 7, "XXXXX").toString();
    mobileNumTextView.setText(alterStr);
    alertDialogBuilder = new AlertDialog.Builder(SignUpActivity.this);
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setView(view);
    alertDialog = alertDialogBuilder.create();
    alertDialog.show();
    setupUI(alertDialog.getWindow().getDecorView());
    view.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        try {
          InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(pinview.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
          e.printStackTrace();
        }


      }
    });
  }

  private void otpValidation(String otp) {

    boolean cancel = false;
    View focusView = null;
    if (pinview.getText().toString().length() < 4) {
      GlobalData.showToast(getBaseContext(), "please enter 4 digits", Toast.LENGTH_SHORT).show();
      focusView = pinview;
      cancel = true;
    }
    if (cancel) {
      focusView.requestFocus();
    } else {
      if (new UtilService().isNetworkAvailable(SignUpActivity.this)) {
        progressDialog = new TransparentProgressDialog(SignUpActivity.this);
        progressDialog.show();
        try {
          HashMap<String, String> map = new HashMap<>();
          map.put("otp", otp);
          map.put("type", "register");
          map.put("username", signup.getData().getUsername());

          restService.OtpValidation(map).enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
              user = response.body();
              if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
              }

              if (user != null && user.getStatus() == 200) {
                getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                        .edit().putString("FCM_TOKEN_ID", "").apply();
                if (Build.VERSION.SDK_INT >= 23) {
                  if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                          == PackageManager.PERMISSION_GRANTED) {
                    File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                            + "/" + ".HYPERM", "PDF");
                    if (f1.exists()) {
                      f1.delete();
                    }
                  }
                }else {
                  File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                          + "/" + ".HYPERM", "PDF");
                  if (f1.exists()) {
                    f1.delete();
                  }
                }
                ((MainApplication) getApplication()).addAccessToken(String.format("Bearer %s", user.getAccess_token().trim()));
                restService = ((MainApplication) getApplication()).getClient();
                Intent i = new Intent(SignUpActivity.this, SetNewPasswordActivity.class);
                i.putExtra("username", signup.getData().getUsername());
                startActivity(i);
                finish();

              } else if (user != null) {
                GlobalData.showToast(getBaseContext(), user.getMessage(), Toast.LENGTH_SHORT).show();

              } else if (response.errorBody() != null) {
                Gson gson = new Gson();
                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();

              }


            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
              if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
              }
              GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
          });

        } catch (Exception e) {
          e.printStackTrace();
        }
      } else {
        GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
      }
    }

  }


  @Override
  public void onBackPressed() {
    super.onBackPressed();
    this.overridePendingTransition(R.anim.animation_f_enter,
            R.anim.animation_f_leave);
  }

  private void setupWindowAnimations() {
    this.overridePendingTransition(R.anim.animation_enter,
            R.anim.animation_leave);
  }

  public void setupUI(View view) {
    try {
      if (!(view instanceof EditText)) {
        view.setOnTouchListener(new View.OnTouchListener() {
          @SuppressLint("ClickableViewAccessibility")
          public boolean onTouch(View v, MotionEvent event) {
            hideSoftKeyboard(SignUpActivity.this);
            return false;
          }
        });
      }

      if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
          View innerView = ((ViewGroup) view).getChildAt(i);
          setupUI(innerView);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}