package com.retrytech.strangerapp.activity;

import static com.retrytech.strangerapp.utils.GoogleLoginManager.RC_SIGN_IN;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
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.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityLoginBinding;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;
import com.retrytech.strangerapp.utils.GoogleLoginManager;
import com.retrytech.strangerapp.utils.SessionManager;

import java.util.HashMap;

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

public class LoginActivity extends AppCompatActivity {
    ActivityLoginBinding binding;
    SessionManager sessionManager;
    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_login);
        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)));

        sessionManager = new SessionManager(this);

        GoogleLoginManager googleLoginManager = new GoogleLoginManager(this);

        binding.tvPrivacy.setOnClickListener(view -> {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sessionManager.getAppSettings().getMiscs().getPrivcyUrl()));
            startActivity(browserIntent);
        });

        binding.tvTerms.setOnClickListener(view -> {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sessionManager.getAppSettings().getMiscs().getTerms()));
            startActivity(browserIntent);
        });

        binding.loutGoogleLogin.setOnClickListener(view ->
                googleLoginManager.onLogin());
        binding.loutEmailLogin.setOnClickListener(v -> startActivity(new Intent(this, EmailLoginActivity.class)));

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    public void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            if (account != null) {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("identity", account.getEmail());
                hashMap.put("fullname", account.getDisplayName());
                callApiForRegister(hashMap);
            }
        } catch (ApiException ignored) {
            Log.d("TAG", "");
        }
    }

    private void callApiForRegister(HashMap<String, Object> hashMap) {
        dialog.show();
        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(LoginActivity.this, "Sign in Successful", Toast.LENGTH_SHORT).show();
                        sessionManager.saveUser(user);
                        dialog.dismiss();
                        if (user.getData().getGender() == -1) {
                            startActivity(new Intent(LoginActivity.this, GenderSelectActivity.class));
                        } else {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        }
                        finishAffinity();

                    }

                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
//
            }
        });
    }


}