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.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.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
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.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.gyf.immersionbar.ImmersionBar;
import com.file.clean.q.R;
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 SharedPreferences sharedPreferences;
    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;
    @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();
//        sharedPreferences = getSharedPreferences("AppPreferences", MODE_PRIVATE);

        Log.e("NOTIFICATIONS", "NOTIFICATIONS 1");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            Log.e("NOTIFICATIONS", "NOTIFICATIONS 2");
//            String[] stringArray = {Manifest.permission.POST_NOTIFICATIONS};
//            launcher.launch(stringArray, null);
//        }

        if (GlobalConfig.INSTANCE.isInit()) {
            showOpenAd();
            //点击过start
            binding.startId.setVisibility(View.GONE);
            binding.llAgreement.setVisibility(View.GONE);
//            binding.lottieAnimattionView.setVisibility(View.VISIBLE);
//            startAnimation();
            binding.progressBar.setVisibility(View.VISIBLE);
            binding.loadingId.setVisibility(View.VISIBLE);
            startProgressAnimation();
        } else {
            //未点击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();
                    startActivity(new Intent(StartActivity.this,MainActivity.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 startAnimation() {
        binding.lottieAnimattionView.setAnimation(R.raw.sp_anim);
        // 播放动画
        binding.lottieAnimattionView.playAnimation();
        // 暂停动画
        // lottieAnimationView.pauseAnimation();
        // 停止动画
        // lottieAnimationView.cancelAnimation();

        binding.lottieAnimattionView.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(@NonNull Animator animator) {
                // 动画开始时调用  初始化广告
//                initializeThirdPartySDKsAndUserData();
            }

            @Override
            public void onAnimationEnd(@NonNull Animator animator) {
                // 动画结束时调用  动画结束后跳转首页
//                goToMainActivity();
            }

            @Override
            public void onAnimationCancel(@NonNull Animator animator) {
                // 动画被取消时调用
            }

            @Override
            public void onAnimationRepeat(@NonNull Animator animator) {
                // 动画重复时调用
            }
        });
    }

    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);
                showOpenAd();
                //加载动画
                binding.startId.setVisibility(View.GONE);
                binding.llAgreement.setVisibility(View.GONE);
                //加载动画
                startProgressAnimation();
                binding.progressBar.setVisibility(View.VISIBLE);
                binding.loadingId.setVisibility(View.VISIBLE);
                CleanApplication.Companion.init();
            }
        });
    }

//    private void initializeThirdPartySDKsAndUserData() {
//        // 在这里执行第三方 SDK 的初始化和其他数据读取操作
//    }

    private void showOpenAd() {
        AdmobManager.INSTANCE.init(this, (ret) -> {
            if (isFinishing() || isDestroyed()) return null;
            if (ret == 0) {
                AdmobManager.INSTANCE.showAppOpenAd(this,
                        () -> {
                            jumpNext("showAppOpenAd 1");
                            return null;
                        },
                        () -> {
                            animator.cancel();
                            binding.progressBar.setProgress(100);
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            return null;
                        },
                        () -> {
                            jumpNext("showAppOpenAd 2");
                            return null;
                        }, false
                    );
            } else if (ret == 1) {
                AdmobManager.INSTANCE.showInterstitialAd(this,
                        () -> {
                            jumpNext("showInterstitialAd 1");
                            return null;
                        },
                        () -> {
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            animator.cancel();
                            binding.progressBar.setProgress(100);
                            binding.progressBar.setVisibility(View.GONE);
                            return null;
                        },
                        () -> {
                            jumpNext("showInterstitialAd 2");
                            return null;
                        }, false
                );
            }
            return null;
        }, () -> {
            jumpNext("showAppOpenAd 3");
            return null;
        });
    }

    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 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)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, CleanJunkActivity.class));
            finish();
            return;
        }

        if (Objects.equals(actionId, GlobalConfig.ID_APPMANAGER)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, BatteryInfoActivity.class));
            finish();
            return;
        }

        if (Objects.equals(actionId, GlobalConfig.ID_BATTERY_INFO)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, InfoActivity.class));
            finish();
            return;
        }

        if (Objects.equals(actionId, GlobalConfig.ID_LARGE_FILE_CLEANER)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, LargeFileActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_WHATSAPP)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, WhatsAppActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_APP_PROCESS)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, AppProcessActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_SIMILAR_PHOTOS)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, SimilarPhotosActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, GlobalConfig.ID_SCREENSHOT_CLEAN)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, ScreenShotActivity.class));
            finish();
            return;
        }
        startActivity(new Intent(this, MainActivity.class));
        finish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.lottieAnimattionView != null) {
            binding.lottieAnimattionView.cancelAnimation(); // 停止动画
            binding.lottieAnimattionView.clearAnimation(); // 清除动画
            binding.lottieAnimattionView.setImageDrawable(null); // 清除图像
            binding.lottieAnimattionView.destroyDrawingCache(); // 销毁缓存
        }
        nonBlockingCountdown.cancel();
        if (animator!=null){
            animator.cancel();
        }
    }
}