package com.file.clean.q.view.activity;
//import static com.scream.scream.qq.model.bean.Global.FUNCTION_SIMILAR_PHOTOS;
import static com.file.clean.q.GlobalConfig.ID_MALWARE_CLEAN;
import static com.file.clean.q.GlobalConfig.ID_WHEATHER;
import static com.file.clean.q.GlobalConfig.URL_PRIVACY;
import static com.file.clean.q.model.bean.Global.OpenLoadTime;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.animation.ValueAnimator;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.file.clean.q.CleanApplication;
import com.file.clean.q.GlobalConfig;
import com.file.clean.q.business.EventUtils;
import com.file.clean.q.business.admob.AdmobManager;
import com.file.clean.q.business.newAdmob.AdmobHelps;
import com.file.clean.q.model.util.PermissionUtils;
import com.file.clean.q.util.ActivityLauncher;
import com.file.clean.q.util.NonBlockingCountdown;
import com.file.clean.q.util.SPUtils;
import com.file.clean.q.view.MainActivity;
import com.file.clean.q.view.weather.WeatherInterface;
import com.gyf.immersionbar.ImmersionBar;
import com.file.clean.q.databinding.ActivityStartBinding;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;


public class StartActivity extends AppCompatActivity {
    private ActivityResultLauncher<String> requestNotificationPermissionLauncher;
    ActivityStartBinding binding;
    private ActivityResultLauncher<String[]> multiplePermissionsLauncher;
    private ActivityResultLauncher<Intent> notificationSettingsLauncher;
    private boolean adShowing = false;
    private NonBlockingCountdown nonBlockingCountdown = new NonBlockingCountdown(this::jumpNext);
    private int outJumpTime = SPUtils.Companion.getInstance().getInt(OpenLoadTime, 15);
    public AtomicBoolean jumped = new AtomicBoolean(false);
    private ActivityLauncher launcher;
    private ValueAnimator animator;
    private Handler handler = new Handler(Looper.getMainLooper());
    SharedPreferences preferences = CleanApplication.context.getGuideSharedPreferences();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStartBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        launcher = new ActivityLauncher(this);
        EventUtils.INSTANCE.event("page_StartActivity", "", null);
        initBar();
        initPermission();

        Log.e("NOTIFICATIONS", "NOTIFICATIONS 1");
        if (GlobalConfig.INSTANCE.isInit()) {
            showOpenAd();
            //点击过start
            binding.startId.setVisibility(View.GONE);
            binding.loadTop.setVisibility(View.VISIBLE);
            binding.llConsent.setVisibility(View.GONE);
            binding.llAgreement.setVisibility(View.GONE);
            binding.progressBar.setVisibility(View.VISIBLE);
            binding.loadingId.setVisibility(View.VISIBLE);
            startProgressAnimation();
        } else {
            binding.loadTop.setVisibility(View.GONE);
            binding.llConsent.setVisibility(View.VISIBLE);
            //未点击start
            setupStartButton();
            //协议
            setupAgreementTextView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!adShowing && GlobalConfig.INSTANCE.isInit()) {
            nonBlockingCountdown.start(outJumpTime);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        nonBlockingCountdown.cancel();
    }
    private void startProgressAnimation() {
        animator = ValueAnimator.ofInt(0, 100);
        animator.setDuration(15000); // 15秒
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int progress = (int) animation.getAnimatedValue();
                binding.progressBar.setProgress(progress);
                if (progress == 100) {
                    nonBlockingCountdown.cancel();
                    boolean isGuideSP = preferences.getBoolean("isGuideSP", false);
                    if (isGuideSP || isCleaned()) {
                        startActivity(new Intent(StartActivity.this, MainActivity.class));
                        finish();
                    } else {
                        startActivity(new Intent(StartActivity.this, WhickActivity.class));
                        finish();
                    }
                }
            }
        });
        animator.start();
    }
    private void initPermission() {
        multiplePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    if (result.get(Manifest.permission.POST_NOTIFICATIONS) != null && result.get(Manifest.permission.POST_NOTIFICATIONS)) {
                        permissionGranted();
                    }
                }
        );


        notificationSettingsLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 处理结果
                }
        );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                PermissionUtils.requestNotificationPermission(StartActivity.this, notificationSettingsLauncher, multiplePermissionsLauncher);
            }
        }
    }

    private void permissionGranted() {
        // 处理权限被授予的情况
    }

    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(true)  // 状态栏字体颜色为深色
                .navigationBarDarkIcon(false)  // 导航栏图标颜色为浅色
                .init();
    }

    private void setupStartButton() {
        binding.loadingId.setVisibility(View.GONE);
        binding.progressBar.setVisibility(View.GONE);
        binding.startId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalConfig.INSTANCE.setInit(true);
                EventUtils.INSTANCE.event("app_start", "", null);
                nonBlockingCountdown.start(outJumpTime);
                showOpenAdFlase();
                //加载动画
                binding.startId.setVisibility(View.GONE);
                binding.llConsent.setVisibility(View.GONE);
                binding.llAgreement.setVisibility(View.GONE);
                binding.loadTop.setVisibility(View.VISIBLE);
                //加载动画
                startProgressAnimation();
                binding.progressBar.setVisibility(View.VISIBLE);
                binding.loadingId.setVisibility(View.VISIBLE);
                CleanApplication.Companion.init();
            }
        });
    }

    private void showOpenAd() {
        AdmobHelps.INSTANCE.init(this, (ret) -> {
//            Log.d("showAppOpenAd", "111");
            if (isFinishing() || isDestroyed()) return null;
            int notificationId = getIntent().getIntExtra(GlobalConfig.KEY_NOTIFICATION_ID, -1);
            int appBackground = getIntent().getIntExtra(GlobalConfig.KEY_APP_BACKGROUND, -1);
            if (notificationId != -1 || appBackground == 1) {
                Log.d("showAppOpenAd11", "111");
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (ret == 0) {
                            Log.d("showAppOpenAd", "222");
                            if (AdmobHelps.INSTANCE.isShowOpenAd()){
                                AdmobHelps.INSTANCE.showAppOpenAd(StartActivity.this,
                                        () -> {
                                            jumpNext("showAppOpenAd 1");
                                            Log.d("showAppOpenAd", "333");
                                            return null;
                                        },
                                        () -> {
                                            binding.progressBar.setProgress(100);
                                            animator.cancel();
                                            adShowing = true;
                                            nonBlockingCountdown.cancel();
                                            Log.d("showAppOpenAd", "444");
                                            return null;
                                        },
                                        () -> {
                                            jumpNext("showAppOpenAd 2");
                                            Log.d("showAppOpenAd", "555");
                                            return null;
                                        }, false
                                );
                            }else {
                                jumpNext("showAppOpenAd 2");
                            }

                        } else if (ret == 1) {
                            if (AdmobHelps.INSTANCE.isShowAdInter()) {
                                AdmobHelps.INSTANCE.showInterstitialAd(
                                        StartActivity.this,
                                        () -> {
                                            jumpNext("showInterstitialAd 1");
                                            // 当广告被关闭时的逻辑
                                            Log.d("AdmobHelps", "Interstitial Ad was dismissed.");
                                            return null;
                                        },
                                        () -> {
                                            // 当广告展示完成时的逻辑
                                            binding.progressBar.setProgress(100);
                                            animator.cancel();
                                            adShowing = true;
                                            nonBlockingCountdown.cancel();
                                            Log.d("AdmobHelps", "Interstitial Ad was shown.");
                                            return null;
                                        },
                                        () -> {
                                            jumpNext("showInterstitialAd 2");
                                            // 当广告加载失败时的逻辑
                                            Log.d("AdmobHelps", "Interstitial Ad failed to load.");
                                            return null;
                                        },
                                        false,true
                                );
                            } else {
                                jumpNext("showInterstitialAd 1");
                            }
                        }
                    }
                }, 3000);
            } else {
                if (ret == 0) {
                    Log.d("showAppOpenAd11", "222");
                    if (AdmobHelps.INSTANCE.isShowOpenAd()){
                        AdmobHelps.INSTANCE.showAppOpenAd(this,
                                () -> {
                                    jumpNext("showAppOpenAd 1");
                                    Log.d("showAppOpenAd", "333");
                                    return null;
                                },
                                () -> {
                                    binding.progressBar.setProgress(100);
                                    animator.cancel();
                                    adShowing = true;
                                    nonBlockingCountdown.cancel();
                                    Log.d("showAppOpenAd", "444");
                                    return null;
                                },
                                () -> {
                                    jumpNext("showAppOpenAd 2");
                                    Log.d("showAppOpenAd", "555");
                                    return null;
                                }, false
                        );
                    }else {
                        jumpNext("showAppOpenAd 2");
                    }
                } else if (ret == 1) {
                    if (AdmobHelps.INSTANCE.isShowAdInter()) {
                        AdmobHelps.INSTANCE.showInterstitialAd(
                                StartActivity.this,
                                () -> {
                                    jumpNext("showInterstitialAd 1");
                                    // 当广告被关闭时的逻辑
                                    Log.d("AdmobHelps", "Interstitial Ad was dismissed.");
                                    return null;
                                },
                                () -> {
                                    binding.progressBar.setProgress(100);
                                    animator.cancel();
                                    // 当广告展示完成时的逻辑
                                    adShowing = true;
                                    nonBlockingCountdown.cancel();
                                    Log.d("AdmobHelps", "Interstitial Ad was shown.");
                                    return null;
                                },
                                () -> {
                                    jumpNext("showInterstitialAd 2");
                                    // 当广告加载失败时的逻辑
                                    Log.d("AdmobHelps", "Interstitial Ad failed to load.");
                                    return null;
                                },
                                false,
                                true
                        );
                    } else {
                        jumpNext("showInterstitialAd 1");
                    }
                }
            }
            return null;
        }, () -> {
            jumpNext("showAppOpenAd 3");
            Log.d("showAppOpenAd", "999");
            return null;
        });
    }
    private void showOpenAdFlase() {
        AdmobHelps.INSTANCE.init(this, (ret) -> {
            Log.d("showAppOpenAd", "111");
            if (isFinishing() || isDestroyed()) return null;
            if (ret == 0) {
                Log.d("showAppOpenAd", "222");
                if (AdmobHelps.INSTANCE.isShowOpenAd()){
                    AdmobHelps.INSTANCE.showAppOpenAd(this,
                            () -> {

                                startIntent();
                                Log.d("showAppOpenAd", "333");
                                return null;
                            },
                            () -> {
                                binding.progressBar.setProgress(100);
                                animator.cancel();
                                adShowing = true;
                                nonBlockingCountdown.cancel();
                                Log.d("showAppOpenAd", "444");
                                return null;
                            },
                            () -> {
                                startIntent();
                                Log.d("showAppOpenAd", "555");
                                return null;
                            }, false
                    );
                }else {
                    startIntent();
                }
            } else if (ret == 1) {
                if (AdmobHelps.INSTANCE.isShowAdInter()) {
                    AdmobHelps.INSTANCE.showInterstitialAd(
                            StartActivity.this,
                            () -> {

                                startIntent();
                                // 当广告被关闭时的逻辑
                                Log.d("AdmobHelps", "Interstitial Ad was dismissed.");
                                return null;
                            },
                            () -> {
                                binding.progressBar.setProgress(100);
                                animator.cancel();
                                // 当广告展示完成时的逻辑
                                adShowing = true;
                                nonBlockingCountdown.cancel();
                                Log.d("AdmobHelps", "Interstitial Ad was shown.");
                                return null;
                            },
                            () -> {
                                startIntent();
                                // 当广告加载失败时的逻辑
                                Log.d("AdmobHelps", "Interstitial Ad failed to load.");
                                return null;
                            },
                            false,
                            true
                    );
                } else {
                    startIntent();
                }
            }
            return null;
        }, () -> {
            startIntent();
            Log.d("showAppOpenAd", "999");
            return null;
        });
    }
    private void startIntent() {
        startActivity(new Intent(this, WhickActivity.class));
        finish();
    }
    private void setupAgreementTextView() {
        binding.userAgreement.setOnClickListener(v -> {
            Uri uri = Uri.parse(GlobalConfig.URL_AGREEMENT);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "No app can handle this action", Toast.LENGTH_SHORT).show();
            }
        });
        binding.privacyPolicy.setOnClickListener(v -> {
            Uri uri = Uri.parse(URL_PRIVACY);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "No app can handle this action", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("jumpNext", "onNewIntent jumped=" + jumped.get());
        jumpNext("onNewIntent");
    }
    private boolean isCleaned() {
        SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        return prefs.getBoolean("cleaned", false);
    }
    private void jumpNext(String where) {
        Log.e("jumpNext", "jumped=" + jumped.get() + " where=" + where);
        if (jumped.get()) return;
        jumped.set(true);
        int actionId = getIntent().getIntExtra(GlobalConfig.KEY_NOTIFICATION_ID,-1) ;
        Log.e("jumpNext", "actionId=" + actionId);

        if (Objects.equals(actionId, GlobalConfig.ID_CLEAN_JUNK)) {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator", 1);
            startActivity(intent);
            return;
        }

        if (Objects.equals(actionId, GlobalConfig.ID_BATTERY_INFO)) {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator", 2);
            startActivity(intent);
            return;
        }

        if (Objects.equals(actionId, GlobalConfig.ID_LARGE_FILE_CLEANER)) {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator", 3);
            startActivity(intent);
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_SIMILAR_PHOTOS)) {
            startActivity(new Intent(this, SimilarPhotosActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_SCREENSHOT_CLEAN)) {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator", 4);
            startActivity(intent);
            return;
        }
        if (Objects.equals(actionId, ID_WHEATHER)) {
            startActivity(new Intent(this, WeatherInterface.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_MALWARE_CLEAN)) {
            startActivity(new Intent(this, MalwareCleanActivity.class));
            finish();
            return;
        }

        boolean isGuideSP = preferences.getBoolean("isGuideSP", false);
        if (isGuideSP || isCleaned()) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        } else {
            startActivity(new Intent(this, WhickActivity.class));
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        nonBlockingCountdown.cancel();
        multiplePermissionsLauncher = null;
        notificationSettingsLauncher = null;
        if (animator!=null){
            animator.cancel();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (preferences!=null){

        }
    }
}