package com.retrytech.strangerapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityEmailLoginBinding;
import com.retrytech.strangerapp.databinding.ItemForgotPassBinding;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;
import com.retrytech.strangerapp.utils.SessionManager;

import java.util.HashMap;

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

public class EmailLoginActivity extends AppCompatActivity {
    ActivityEmailLoginBinding binding;
    private Dialog dialog;
    private SessionManager sessionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View decorView = getWindow().getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
            return defaultInsets.replaceSystemWindowInsets(
                    defaultInsets.getSystemWindowInsetLeft(),
                    0,
                    defaultInsets.getSystemWindowInsetRight(),
                    defaultInsets.getSystemWindowInsetBottom());
        });
        ViewCompat.requestApplyInsets(decorView);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        binding = DataBindingUtil.setContentView(this, R.layout.activity_email_login);
        initDialog();
        initListener();
    }

    private void initDialog() {
        sessionManager = new SessionManager(this);
        dialog = new Dialog(this);
        View dialogueView = LayoutInflater.from(this).inflate(R.layout.item_loader, null, false);
        dialog.setContentView(dialogueView);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, android.R.color.transparent)));
    }

    private void initListener() {
        binding.imgBack.setOnClickListener(v -> onBackPressed());
        binding.lytNewHere.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
        binding.btnLogin.setOnClickListener(v -> {
            String email = binding.etEmail.getText().toString();
            String password = binding.etPassword.getText().toString();
            if (email.isEmpty()) {
                Toast.makeText(this, R.string.enter_your_mail, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!Const.isEmailValid(email)) {
                Toast.makeText(this, R.string.please_enter_valid_email_, Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, R.string.enter_password, Toast.LENGTH_SHORT).show();
                return;
            }
            FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
            dialog.show();
            firebaseAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(authResult -> {
                if (authResult.getUser() != null && firebaseAuth.getCurrentUser() != null) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("identity", firebaseAuth.getCurrentUser().getEmail());
//                    hashMap.put("fullname", firebaseAuth.getCurrentUser().getDisplayName());
                    callApiForRegister(hashMap);
                } else {
                    dialog.dismiss();
                }
            }).addOnFailureListener(e -> {
                dialog.dismiss();
                Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            });
            ;
        });
        binding.lytForgot.setOnClickListener(v -> {
            BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
            ItemForgotPassBinding forgotPassBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.item_forgot_pass, null, false);
            forgotPassBinding.btnSend.setOnClickListener(v1 -> {
                String email = forgotPassBinding.edtEmail.getText().toString();
                if (email.isEmpty()) {
                    Toast.makeText(this, R.string.enter_your_mail, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog.show();
                FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
                firebaseAuth.sendPasswordResetEmail(email).addOnSuccessListener(command -> {
                    Toast.makeText(this, R.string.email_sent_successfully, Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }).addOnFailureListener(e -> {
                    dialog.dismiss();
                    Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                });
                ;
            });
            forgotPassBinding.ivClose.setOnClickListener(v1 -> bottomSheetDialog.dismiss());
            bottomSheetDialog.setContentView(forgotPassBinding.getRoot());
            bottomSheetDialog.show();
        });
    }

    private void callApiForRegister(HashMap<String, Object> hashMap) {
        Call<User> call = RetrofitClient.getService().registerUser(Const.API_KEY, hashMap);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.body() != null) {
                    User user = response.body();

                    if (user.getData() != null) {
                        Toast.makeText(EmailLoginActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                        sessionManager.saveUser(user);
                        if (user.getData().getGender() == -1) {
                            startActivity(new Intent(EmailLoginActivity.this, GenderSelectActivity.class));
                        } else {
                            startActivity(new Intent(EmailLoginActivity.this, MainActivity.class));
                        }
                        finishAffinity();

                    }

                }
                dialog.dismiss();
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
//
                runOnUiThread(() -> {
                    dialog.dismiss();
                });
            }
        });
    }
}