package com.retrytech.strangerapp.activity;

import android.app.Dialog;
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.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;

import com.google.firebase.auth.FirebaseAuth;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityRegisterBinding;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;

import java.util.HashMap;

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

public class RegisterActivity extends AppCompatActivity {
    ActivityRegisterBinding binding;
    private Dialog dialog;

    @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_register);
        initDialog();
        initListener();
    }

    private void initDialog() {
        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.btnRegister.setOnClickListener(v -> {
            String fullName = binding.etFullname.getText().toString();
            String email = binding.etEmail.getText().toString();
            String password = binding.etPassword.getText().toString();
            String reTypePassword = binding.etReTypePassword.getText().toString();
            if (fullName.isEmpty()) {
                Toast.makeText(this, R.string.enter_full_name, Toast.LENGTH_SHORT).show();
                return;
            }
            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;
            }
            if (reTypePassword.isEmpty()) {
                Toast.makeText(this, R.string.enter_re_type_password, Toast.LENGTH_SHORT).show();
                return;
            }
            if (!reTypePassword.equals(password)) {
                Toast.makeText(this, R.string.password_does_not_match_, Toast.LENGTH_SHORT).show();
                return;
            }
            FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
            dialog.show();
            firebaseAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(authResult -> {
                if (authResult.getUser() != null) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("identity", authResult.getUser().getEmail());
                    hashMap.put("fullname", fullName);
                    callApiForRegister(hashMap);
                }
                dialog.dismiss();
            }).addOnFailureListener(e -> {
                dialog.dismiss();
                Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).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(@NonNull Call<User> call, @NonNull Response<User> response) {
                if (response.body() != null) {
                    User user = response.body();

                    if (user.getData() != null) {
                        Toast.makeText(RegisterActivity.this, "Create Account Successful", Toast.LENGTH_SHORT).show();
//                        if (user.getData().getGender() == -1) {
//                            startActivity(new Intent(RegisterActivity.this, GenderSelectActivity.class));
//                        } else {
//                            startActivity(new Intent(RegisterActivity.this, MainActivity.class));
//                        }
                        onBackPressed();
                    }
                }
                dialog.dismiss();
            }

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

}