package com.friendvilla.bucksbuddy;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.friendvilla.bucksbuddy.MainActivity.USER;
import static com.friendvilla.bucksbuddy.Method.calWallet;
import static com.friendvilla.bucksbuddy.Method.taxCal;
import static com.friendvilla.bucksbuddy.Method.title;
import static com.friendvilla.bucksbuddy.Method.updateUser;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.friendvilla.bucksbuddy.adapter.AmountAdapter;
import com.friendvilla.bucksbuddy.controls.FlipAnimator;
import com.friendvilla.bucksbuddy.model.User;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class NumberActivity extends AppCompatActivity {

    private int Number = 0;
    private Handler handler;
    private Runnable runnable;
    private boolean isShow = false;
    private FlipAnimator animator;
    private LottieAnimationView anim;
    private RecyclerView amtView,numView;
    private MediaPlayer winMediaPlayer,looseMediaPlayer;
    private final List<Integer> rewardList = new ArrayList<>();
    public static MutableLiveData<Integer> AmountNumber = new MutableLiveData<>();

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number); handler = new Handler();
        ((TextView)findViewById(R.id.tvTitle)).setText(title(this,getString(R.string.guess_to_win),6));
        findViewById(R.id.bal).setOnClickListener(view -> startActivity(new Intent(this,WalletActivity.class)));
        User user = USER.getValue(); assert user != null;
        BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
        ((TextView)findViewById(R.id.tvBal)).setText("₹ " + bal);
        anim = findViewById(R.id.win); AmountNumber.setValue(0); Number = 0;
        winMediaPlayer = MediaPlayer.create(this,R.raw.win);
        looseMediaPlayer = MediaPlayer.create(this,R.raw.wrong);
        numView = findViewById(R.id.numView); amtView = findViewById(R.id.amountView);
        numView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        amtView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        AmountNumber.observe(this,integer -> {
            if(integer != 0) {
                for (int i = 0; i < 4; i++) {
                    int num = new Random().nextInt(81) + 10;
                    rewardList.add(num);
                }
                numView.setAdapter(new NumberAdapter(false));
                numView.setVisibility(View.VISIBLE);hidePrice();
                int r = new Random().nextInt(rewardList.size());
                ((TextView) findViewById(R.id.after)).setText("" + rewardList.get(r));
            }
        });
        numView.setHasFixedSize(false);amtView.setHasFixedSize(false);
        amtView.setAdapter(new AmountAdapter(false,5));
        findViewById(R.id.ivMenu).setOnClickListener(view -> {
            if(isShow) {
                assert AmountNumber.getValue() != null;
                updateUser(this,calWallet(AmountNumber.getValue())[0],calWallet(AmountNumber.getValue())[1],String.valueOf(0));
            }
            if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
                winMediaPlayer.stop();
            }
            if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
                looseMediaPlayer.stop();
            }
            if(handler != null & runnable != null) {
                handler.removeCallbacks(runnable);
            }
            finish();
        });
        findViewById(R.id.container).setOnClickListener(v -> {
            assert AmountNumber.getValue() != null;
            int betAmt = AmountNumber.getValue();
            int DEPOSIT = new BigDecimal(user.getDeposit()).intValue();
            int WITHDRAW = new BigDecimal(user.getWithdraw()).intValue();
            int TOTAL = DEPOSIT + WITHDRAW;
            if(AmountNumber.getValue() != null && AmountNumber.getValue() == 0) {
                makeText(this,"Select bet amount",LENGTH_SHORT).show();
            } else if(Number == 0) {
                makeText(this,"Choose number",LENGTH_SHORT).show();
            } else if(DEPOSIT < betAmt && WITHDRAW < betAmt && TOTAL < betAmt) {
                makeText(this,"You have not enough money",LENGTH_SHORT).show();
            } else {
                runnable = () -> {
                    int win = 0;
                    int r = Integer.parseInt(((TextView)findViewById(R.id.after)).getText().toString());
                    if(r == Number) {
                        anim.setVisibility(View.VISIBLE);
                        anim.playAnimation(); win = betAmt * 2;
                        playSound(winMediaPlayer);
                    } else {
                        playSound(looseMediaPlayer);
                    }
                    updateUser(this,calWallet(betAmt)[0],calWallet(betAmt)[1],String.valueOf(taxCal(win)));
                    AmountNumber.setValue(0);rewardList.clear();
                    numView.setVisibility(View.GONE);isShow = false;
                    amtView.setAdapter(new AmountAdapter(false,5));
                };
                showPrice();
            }
        });
        if(!new String(Base64.decode(BuildConfig.PACKAGE,Base64.DEFAULT)).equals(BuildConfig.APPLICATION_ID)) {
            finish();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        USER.observe(this, user -> {
            BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
            ((TextView)findViewById(R.id.tvBal)).setText("₹ " + bal);
        });
    }

    private class NumberAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private boolean tick;
        public NumberAdapter(boolean select) {
            this.tick = select;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.num,parent,false);
            return new CateView(view);
        }

        @SuppressLint({"SetTextI18n", "NotifyDataSetChanged", "RecyclerView"})
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            CateView cateView = (CateView) holder;
            cateView.title.setText("" + rewardList.get(position));
            if(tick && Number == rewardList.get(position)) {
                cateView.title.setBackground(AppCompatResources.getDrawable(NumberActivity.this,R.drawable.right));
            } else {
                cateView.title.setBackground(AppCompatResources.getDrawable(NumberActivity.this,R.drawable.hole));
            }
            cateView.itemView.setOnClickListener(v -> {
                tick = true;
                Number = rewardList.get(position);
                notifyDataSetChanged();
            });
            cateView.itemView.setAnimation(AnimationUtils.loadAnimation(NumberActivity.this,R.anim.party));
        }

        @Override
        public int getItemCount() {
            return rewardList.size();
        }

        private class CateView extends RecyclerView.ViewHolder {
            private final TextView title;
            public CateView(@NonNull View itemView) {
                super(itemView);
                title = itemView.findViewById(R.id.num);
            }
        }
    }

    private void showPrice() {
        View befor = findViewById(R.id.before);
        View after = findViewById(R.id.after);
        View container = findViewById(R.id.container);isShow = true;
        animator = new FlipAnimator(befor,after,container.getWidth()/2,container.getHeight()/2);
        animator.setDuration(800); animator.setRotationDirection(FlipAnimator.DIRECTION_Y);
        container.startAnimation(animator); handler.postDelayed(runnable,1000);
    }

    private void hidePrice() {
        View after = findViewById(R.id.before);
        View befor = findViewById(R.id.after);
        View container = findViewById(R.id.container);
        animator = new FlipAnimator(befor,after,container.getWidth()/2,container.getHeight()/2);
        animator.setDuration(800); animator.setRotationDirection(FlipAnimator.DIRECTION_Y);
        container.startAnimation(animator);
    }

    private void playSound(MediaPlayer mp) {
        try {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.pause();
                    mp.seekTo(0);
                }
                mp.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if(isShow) {
            assert AmountNumber.getValue() != null;
            updateUser(this,calWallet(AmountNumber.getValue())[0],calWallet(AmountNumber.getValue())[1],String.valueOf(0));
        }
        if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
            winMediaPlayer.stop();
        }
        if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
            looseMediaPlayer.stop();
        }
        if(handler != null & runnable != null) {
            handler.removeCallbacks(runnable);
        }
        finish();
    }
}