package com.burhanstore.neonbubblequest;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.burhanstore.neonbubblequest.Utils.AppString;
import com.burhanstore.neonbubblequest.Utils.appuser.UserManager;
import com.burhanstore.neonbubblequest.Utils.callback.CoinCallBack;
import com.burhanstore.neonbubblequest.Utils.crequest.CoinCredit;
import com.burhanstore.neonbubblequest.Utils.monetize.AdLoadManager;
import com.burhanstore.neonbubblequest.Utils.monetize.RewardAdManager;
import com.burhanstore.neonbubblequest.act.InviteActivity;
import com.burhanstore.neonbubblequest.act.LeaderActivity;
import com.burhanstore.neonbubblequest.act.PaymentActivity;
import com.burhanstore.neonbubblequest.act.ProfileActivity;
import com.burhanstore.neonbubblequest.databinding.ActivityMainBinding;
import com.facebook.ads.AdSize;
import com.facebook.ads.AdView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;

import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements CoinCallBack {


    ActivityMainBinding binding;
    Activity activity;
    private Dialog winnerDialog;
    boolean ads = false;
    private long backPressedTime = 0;
    private CountDownTimer countDownTimer;
    private MediaPlayer mediaPlayer;
    private boolean isSoundPlaying = false;
    private TextView game_point, game_level;
    String game_win, cpx_appid, pubscale_appid, monlix_appid, uid;
    String fb_bannerid, admob_bannerid;
    int min, max;
    private AdView adView;

    UserManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        activity = this;

        manager = UserManager.Companion.getInstance(activity);
        binding.gameLobby.setVisibility(View.VISIBLE);
        binding.gameView.setVisibility(View.GONE);

        CoinCredit.INSTANCE.setListener(this);


        game_random_point();

        set_gameData();
        startSound();
        GameController.init_dialog(MainActivity.this);

        // Call Kotlin object method
        AdLoadManager.INSTANCE.Sdk_inint(activity);

        AppString.JsonReader jsonReader = new AppString.JsonReader(manager.getSetting().getOffer_survey());
        cpx_appid = jsonReader.get("cpx_appid");
        pubscale_appid = jsonReader.get("pubscale_appid");
        monlix_appid = jsonReader.get("monlix_appid");
        uid = manager.getUser().getU_id();

        AppString.JsonReader jsonReadeAds = new AppString.JsonReader(manager.getSetting().getAd_unit());
        admob_bannerid = jsonReadeAds.get("admob_bannerid");
        fb_bannerid = jsonReadeAds.get("fb_bannerid");


        binding.playNowButton.setOnClickListener(view1 -> {

            GameController.show_dialog();
            Runnable runnableTimer = () -> {

                if (mediaPlayer != null && isSoundPlaying) {
                    mediaPlayer.pause();
                    mediaPlayer.seekTo(0);
                    isSoundPlaying = false;
                }

                binding.gameLobby.setVisibility(View.GONE);
                binding.gameView.setVisibility(View.VISIBLE);

                GameSession.setString(activity, GameSession.USER_PLAY_MODE, "true");
                binding.gameView.loadUrl("javascript:gameStart()");
                GameController.dismiss_dialog();

            };
            Handler handlerTimer = new Handler();
            handlerTimer.postDelayed(runnableTimer, 3000);

        });

        binding.gameView.setWebChromeClient(new WebChromeClient());
        binding.gameView.getSettings().setJavaScriptEnabled(true);
        binding.gameView.getSettings().setDomStorageEnabled(true);
        binding.gameView.getSettings().setAllowFileAccessFromFileURLs(true);
        binding.gameView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        binding.gameView.addJavascriptInterface(new MainActivity.WebAppInterface(activity), "Android");
        binding.gameView.loadUrl("file:///android_asset/bin/unity/unity/data/js/index.html");
        binding.gameView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView viewx, String urlx) {
                binding.gameView.setVisibility(View.GONE);
                if (!urlx.contains("https")) {
                    viewx.loadUrl(urlx);
                    return false;
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlx));
                    startActivity(intent);
                    return true;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // binding.gamePlay.setVisibility(View.VISIBLE);
                    }
                };
                Handler handler = new Handler();
                handler.postDelayed(runnable, 1000);


            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap facIcon) {
            }

        });

        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
            }

            public void onFinish() {
                //  show_videoAd(activity, Const.GAME_VIDEO_AD);
            }
        };
        countDownTimer.start();

        game_click_listener();

        String banner_ad = Const.GAME_BANNER_AD;
        if (banner_ad.equals("admob")) {
            admob_banner();
        } else {
            facebook_banner();
        }


        appInit();


        binding.coinsTextview.setText(Objects.requireNonNull(manager.getUser()).getPoint());
        binding.UName.setText(Objects.requireNonNull(manager.getUser()).getName());
        binding.vipOffer.setOnClickListener(View -> {
            openCustomChrome(
                    "https://offers.cpx-research.com/index.php?app_id=" + cpx_appid + "&ext_user_id=" + uid,
                    this
            );

        });

        binding.todayOffer.setOnClickListener(View -> {
            openCustomChrome(
                    "https://offers.monlix.com/?appid=" + monlix_appid + "&userid=" + uid,
                    activity
            );
        });

        binding.actLy.referBtn.setOnClickListener(View -> {
            Intent intent = new Intent(MainActivity.this, InviteActivity.class);
            startActivity(intent);
        });


        binding.actLy.redeemBtn.setOnClickListener(View -> {
            Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
            startActivity(intent);
        });

        binding.actLy.leaderBtn.setOnClickListener(View -> {
            Intent intent = new Intent(MainActivity.this, LeaderActivity.class);
            startActivity(intent);
        });
        binding.profile.setOnClickListener(View -> {
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            startActivity(intent);
        });


    }

    private void appInit() {


        Glide.with(activity)
                .load(manager.getUser() != null ? manager.getUser().getImage() : null)
                .centerCrop()
                .placeholder(R.drawable.app_icon)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(
                            @Nullable GlideException e,
                            Object model,
                            Target<Drawable> target,
                            boolean isFirstResource
                    ) {
                        return false; // return true if you handled the error
                    }

                    @Override
                    public boolean onResourceReady(
                            Drawable resource,
                            Object model,
                            Target<Drawable> target,
                            DataSource dataSource,
                            boolean isFirstResource
                    ) {
                        return false; // return true if you handled setting manually
                    }
                })
                .into(binding.profile);


    }

    private void game_click_listener() {

    }


    public class WebAppInterface {

        Context mContext;

        WebAppInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void showAd() {


        }

        @JavascriptInterface
        public void showAndroidBanner() {
            //    bannerCanShow = true;
        }


        @JavascriptInterface
        public void successAlert(String aaa) {

            //        Toast.makeText(mContext, "aaaaaaaaa", Toast.LENGTH_SHORT).show();

        }

        @JavascriptInterface
        public void winDialog() {
            win_popup();

        }

        @JavascriptInterface
        public void LoserDialog() {
            lose_popup();
        }

        @JavascriptInterface
        public void levelUpdate(String count) {
            level_count(count);
        }

        @JavascriptInterface
        public void gameScourUpdate(String count) {
            //   PointCouny(count);
        }


        @JavascriptInterface
        public void showRewardedAd() {
            //   rewardedAdCanShow = true;
        }


        @JavascriptInterface
        public void showAlert(String alerttext) {
            Toast.makeText(getApplicationContext(), alerttext, Toast.LENGTH_LONG).show();
        }


        @JavascriptInterface
        public void portrait() {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }


        @JavascriptInterface
        public void landscape() {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @JavascriptInterface
        public void rateThisApp() {
            // launchMarket();
        }

        @JavascriptInterface
        public void shareText(String txt, String title) {
            // launchTextSharer(txt, title);
        }

        @JavascriptInterface
        public void shareThisApp(String txt, String title) {
            // launchSharer(txt, title);
        }

    }


    private void win_popup() {

        activity.runOnUiThread(() -> {
            //    bsShow_InterstitialAd(activity, Const.GAME_WIN_TO_SHOW_INTERSTITIAL_AD);
            winnerDialog = new Dialog(activity);
            winnerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            winnerDialog.setContentView(R.layout.claim_dialog);
            Window window = winnerDialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(window.getAttributes());
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                window.setAttributes(layoutParams);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
            winnerDialog.setCancelable(false);
            ImageView closeBtn = winnerDialog.findViewById(R.id.bs_closeBtn);
            TextView game_point = winnerDialog.findViewById(R.id.game_point);
            ImageView collect_bonus = winnerDialog.findViewById(R.id.collect_bonus);
            game_point.setText(game_win);
            closeBtn.setOnClickListener(v -> {
                winnerDialog.dismiss();
                binding.gameView.loadUrl("javascript:dialogClsoe()");
            });
            collect_bonus.setOnClickListener(v -> {
                winnerDialog.dismiss();


                binding.gameView.loadUrl("javascript:gamelevelUpdate()");
                game_addPoint(game_win);
                game_random_point();
            });
            winnerDialog.show();

        });

    }

    private void lose_popup() {

        activity.runOnUiThread(() -> {
            winnerDialog = new Dialog(activity);
            winnerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            winnerDialog.setContentView(R.layout.loser_dialog);
            Window window = winnerDialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(window.getAttributes());
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                window.setAttributes(layoutParams);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
            winnerDialog.setCancelable(false);
            ImageView bs_closeBtn = winnerDialog.findViewById(R.id.bs_closeBtn);
            ImageView collect_bonus = winnerDialog.findViewById(R.id.collect_bonus);
            bs_closeBtn.setOnClickListener(v -> {
                winnerDialog.dismiss();
                binding.gameView.loadUrl("javascript:loserOption()");
                runnable_section();
            });
            collect_bonus.setOnClickListener(v -> {
                winnerDialog.dismiss();
                binding.gameView.loadUrl("javascript:loserOption()");
                runnable_section();
            });
            winnerDialog.show();
        });

    }

    private void level_count(String cunt) {
        activity.runOnUiThread(() -> {
            GameController.dismiss_dialog();
            GameSession.setString(activity, GameSession.GAME_RANK, cunt);
            binding.gameLevel.setText(cunt);
        });
    }


    private void game_addPoint(String point) {
        // Call Kotlin object method
        RewardAdManager.INSTANCE.fallback1(activity, manager.getSetting().getGame_config(), "Game", "", true, game_win);
    }


    private void set_gameData() {

        if (GameSession.getString(activity, GameSession.GAME_RANK).equals("")) {
            binding.gameLevel.setText("0");
        } else {
            binding.gameLevel.setText(GameSession.getString(activity, GameSession.GAME_RANK));
        }

    }

    private void game_random_point() {

        try {
            min = Integer.parseInt(Const.GAME_WIN_REWARD_MINIMUM);
            max = Integer.parseInt(Const.GAME_WIN_REWARD_MAXIMUM);
        } catch (NumberFormatException e) {
            min = 0;
            max = 10;
        }
        if (max <= min) {
            max = min + 1;
        }
        final int coins_ = new Random().nextInt((max - min) + 1) + min;
        game_win = String.valueOf(coins_);


    }

    private void runnable_section() {
        //     bsShow_InterstitialAd(activity, Const.GAME_WIN_TO_SHOW_INTERSTITIAL_AD);
    }


    private void startSound() {

        if (GameSession.getString(activity, GameSession.USER_PLAY_MODE).equals("true")) {

        } else {
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer.create(this, R.raw.bgsound);
                mediaPlayer.setLooping(true); // Ensures the sound loops
            }

            if (!isSoundPlaying) {
                mediaPlayer.start();
                isSoundPlaying = true;
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        startSound();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopSound();
    }

    private void stopSound() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isSoundPlaying = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    @Override
    public void onBackPressed() {
        if (GameSession.getString(activity, GameSession.USER_PLAY_MODE).equals("true")) {
            binding.gameView.setVisibility(View.GONE);
            binding.gameLobby.setVisibility(View.VISIBLE);
            GameSession.setString(activity, GameSession.USER_PLAY_MODE, "false");
        } else {
            long currentTime = System.currentTimeMillis();
            if (currentTime - backPressedTime > 2000) {
                Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
                backPressedTime = currentTime;
                GameSession.setString(activity, GameSession.USER_PLAY_MODE, "false");
            } else {
                GameSession.setString(activity, GameSession.USER_PLAY_MODE, "false");
                finish();
                super.onBackPressed();
            }
        }
    }


    private void admob_banner() {

        if (binding.mAdView.getAdUnitId() == null) {
            binding.mAdView.setAdUnitId(admob_bannerid);
        }
        binding.mAdView.loadAd(new AdRequest.Builder().build());
        binding.mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Ad loaded callback
            }

            @Override
            public void onAdOpened() {
                // Ad opened callback
            }

            @Override
            public void onAdClicked() {
                // Ad clicked callback
            }

            @Override
            public void onAdClosed() {
                // Ad closed callback
            }
        });


    }

    private void facebook_banner() {
        adView = new AdView(this, fb_bannerid, AdSize.BANNER_HEIGHT_50);
        LinearLayout adContainer = findViewById(R.id.banner_container);
        adContainer.addView(adView);
        adView.loadAd();
    }


    @Override
    public void onCoinReceived(@NotNull String coin) {

        Toast.makeText(
                activity,
                "Coins Successfully Credited !!",
                Toast.LENGTH_SHORT
        ).show();

        AppConst.INSTANCE.setString(
                activity,
                AppConst.USER_COIN,
                coin
        );
        binding.coinsTextview.setText(coin);


    }

    private void openCustomChrome(String url, Activity activity) {
        try {
            CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
            builder.setShowTitle(true);
            builder.setInstantAppsEnabled(true);
            builder.setShareState(CustomTabsIntent.SHARE_STATE_OFF);

            // Optional toolbar color customization
            builder.setToolbarColor(ContextCompat.getColor(activity, R.color.white));

            CustomTabsIntent customTabsIntent = builder.build();
            customTabsIntent.launchUrl(activity, Uri.parse(url));
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "Unable to open link", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();


        binding.coinsTextview.setText(AppConst.INSTANCE.getString(
                activity,
                AppConst.USER_COIN

        ));

    }
}