package com.retrytech.strangerapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityMainBinding;
import com.retrytech.strangerapp.databinding.ItemFreeCoinPopupBinding;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.modal.fakeuser.FakeUser;
import com.retrytech.strangerapp.modal.settings.AppSettings;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;
import com.retrytech.strangerapp.utils.SessionManager;

import java.util.Random;

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

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    SessionManager sessionManager;
    int gender = -1;

    @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_main);
        sessionManager = new SessionManager(this);

        if (sessionManager.getUser().isNewUser() && !sessionManager.getBooleanValue(Const.FREE_COINS_ADDED)) {
            sessionManager.saveBooleanValue(Const.FREE_COINS_ADDED, true);
            showFreeCoinAddedPopup();
        }


        binding.tvCoins.setText(String.valueOf(sessionManager.getUser().getData().getCoins()));
        binding.imgWallet.setOnClickListener(view -> {
            startActivity(new Intent(MainActivity.this, WalletActivity.class));
        });

        int randomInt = new Random().nextInt(999 - 562) + 562;
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        binding.counterTextview
                .setAnimationDuration(5000)
                .setInterpolator(new AccelerateInterpolator())
                .countAnimation(0, randomInt);

        Animation animation = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
        Animation animation2 = AnimationUtils.loadAnimation(this, R.anim.alpha_anim_reverse);
        Animation animation3 = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
        binding.img1.startAnimation(animation);
        binding.img2.startAnimation(animation2);
        binding.img3.startAnimation(animation3);

        binding.btnJoin.setOnClickListener(view -> {
                    if (sessionManager.getUser().getData().getIs_block() == 1) {
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.account_has_been_blocked), Toast.LENGTH_SHORT).show();
                    } else if (sessionManager.getUser().getData().getCoins() == 0 ||
                            ((gender == 1 || gender == 0) && sessionManager.getUser().getData().getCoins() < Integer.parseInt(sessionManager.getAppSettings().getGender().getGendermatch())) ||
                            ((gender == -1) && sessionManager.getUser().getData().getCoins() < Integer.parseInt(sessionManager.getAppSettings().getGender().getBothMatch()))) {
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.insufficient_balance), Toast.LENGTH_SHORT).show();
                    } else {
                        startActivityForResult(new Intent(MainActivity.this, CallActivity.class).putExtra("gender", gender), 200);
                    }
                }
        );

        binding.imgProfile.setOnClickListener(view -> startActivity(new Intent(MainActivity.this, ProfileActivity.class)));

        Glide.with(this)
                .load(Const.ITEM_URL + sessionManager.getUser().getData().getImage())
                .circleCrop()
                .into(binding.imgProfile);

        binding.tvGirlPrice.setText(sessionManager.getAppSettings().getGender().getGendermatch());
        binding.tvGuyPrice.setText(sessionManager.getAppSettings().getGender().getGendermatch());
        binding.tvBothPrice.setText(sessionManager.getAppSettings().getGender().getBothMatch());
        binding.tvDes.setText(getResources().getString(R.string.after_match_call_will_also_cost_you).concat(" ").concat(String.valueOf(sessionManager.getAppSettings().getGender().getCallPriceMin())).concat(" ").concat(getResources().getString(R.string.coins_per_minute)));
        binding.loutBoth.setOnClickListener(view -> {

            gender = -1;
            //            Both Lout
            binding.tvBothPrice.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvBoth.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.loutBoth.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.btn_red)));
            //            Gay Lout
            binding.tvGuyPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvGuy.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutGuy.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));
            //            Girl Lout
            binding.tvGirlPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvGirl.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutGirl.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));

        });

        binding.loutGuy.setOnClickListener(view -> {
            gender = 1;
            //            Both Lout
            binding.tvBothPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvBoth.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutBoth.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));
            //            Guy Lout
            binding.tvGuyPrice.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvGuy.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.loutGuy.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.btn_red)));
            //            Girl Lout
            binding.tvGirlPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvGirl.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutGirl.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));

        });


        binding.loutGirl.setOnClickListener(view -> {
            gender = 0;
            //            Both Lout
            binding.tvBothPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvBoth.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutBoth.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));
            //            Guy Lout
            binding.tvGuyPrice.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.tvGuy.setTextColor(ContextCompat.getColor(this, R.color.black));
            binding.loutGuy.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.white)));
            //            Girl Lout
            binding.tvGirlPrice.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvGirl.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.loutGirl.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.btn_red)));

        });

        if (sessionManager.getUser().getData().getGender() == 1) {
            binding.loutGirl.performClick();
        } else {
            binding.loutGuy.performClick();
        }


    }

    private void fetchFakeUsers() {
        Call<FakeUser> call = RetrofitClient.getService().fetchFakeUsers(Const.API_KEY);
        call.enqueue(new Callback<FakeUser>() {
            @Override
            public void onResponse(Call<FakeUser> call, Response<FakeUser> response) {
                if (response.body() != null) {
                    FakeUser fakeUser = response.body();
                    sessionManager.saveFakeUsers(fakeUser);
                }
            }

            @Override
            public void onFailure(Call<FakeUser> call, Throwable t) {
                Log.d("TAG", "onFailure: " + t.getMessage());
            }
        });
    }

    private void addFreeCoins() {
        Call<AppSettings> call = RetrofitClient.getService().addCoins(Const.API_KEY,
                sessionManager.getUser().getData().getId(),
                sessionManager.getAppSettings().getGender().getDefaultcoin());
        call.enqueue(new Callback<AppSettings>() {
            @Override
            public void onResponse(Call<AppSettings> call, Response<AppSettings> response) {
                if (response.body() != null) {
                    AppSettings settings = response.body();
                    if (settings.isStatus()) {

                    }
                }
            }

            @Override
            public void onFailure(Call<AppSettings> call, Throwable t) {

            }
        });

    }

    private void showFreeCoinAddedPopup() {
        Dialog dialog = new Dialog(this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = LayoutInflater.from(this).inflate(R.layout.item_free_coin_popup, null, false);
        ItemFreeCoinPopupBinding freeCoinPopupBinding = DataBindingUtil.bind(view);

        freeCoinPopupBinding.btnYes.setOnClickListener(view1 -> {
            dialog.dismiss();
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.show();

    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.tvCoins.setText(String.valueOf(sessionManager.getUser().getData().getCoins()));
        FakeUser fakeUser = sessionManager.getFakeUser();
        if (fakeUser == null || fakeUser.getData().isEmpty()) {
            fetchFakeUsers();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            resetUserCallStatus();
        }
    }

    private void resetUserCallStatus() {

        Call<User> call = RetrofitClient.getService().resetUserCallStatus(Const.API_KEY, sessionManager.getUser().getData().getId());
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {

            }

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

            }
        });

    }
}