package com.swiftcleaner.chovey.view.activity;

import static com.swiftcleaner.chovey.GlobalConfig.ID_APPMANAGER;
import static com.swiftcleaner.chovey.GlobalConfig.ID_APP_PROCESS;
import static com.swiftcleaner.chovey.GlobalConfig.ID_BATTERY_INFO;
import static com.swiftcleaner.chovey.GlobalConfig.ID_CLEAN_JUNK;
import static com.swiftcleaner.chovey.GlobalConfig.ID_LARGE_FILE_CLEANER;
import static com.swiftcleaner.chovey.GlobalConfig.ID_SCREENSHOT_CLEAN;
import static com.swiftcleaner.chovey.GlobalConfig.ID_SIMILAR_PHOTOS;
import static com.swiftcleaner.chovey.GlobalConfig.ID_WHATSAPP;
import static com.swiftcleaner.chovey.GlobalConfig.ID_WHEATHER;
import static com.swiftcleaner.chovey.GlobalConfig.ID_XINGZUO;
import static com.swiftcleaner.chovey.GlobalConfig.KEY_NOTIFICATION_ID;
import static com.swiftcleaner.chovey.GlobalConfig.URL_PRIVACY;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_APP_MANAGER;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_APP_PROCESS;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_BATTERY;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_CLEAN;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_LARGE_FILE;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_SCREENSHOT;
//import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_SIMILAR_PHOTOS;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_SIMILAR_PHOTOS;
import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_WHATS_APP;
import static com.swiftcleaner.chovey.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.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.util.Log;
import android.view.View;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.CleanApplication;
import com.swiftcleaner.chovey.GlobalConfig;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.EventUtils;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.databinding.ActivityStartBinding;
import com.swiftcleaner.chovey.model.util.PermissionUtils;
import com.swiftcleaner.chovey.util.ActivityLauncher;
import com.swiftcleaner.chovey.util.NonBlockingCountdown;
import com.swiftcleaner.chovey.util.SPUtils;
import com.swiftcleaner.chovey.view.MainActivity;
import com.swiftcleaner.chovey.view.activity.AppProcessActivity;
import com.swiftcleaner.chovey.view.activity.BatteryInfoActivity;
import com.swiftcleaner.chovey.view.activity.CleanJunkActivity;
import com.swiftcleaner.chovey.view.activity.InfoActivity;
import com.swiftcleaner.chovey.view.activity.LargeFileActivity;
import com.swiftcleaner.chovey.view.activity.ScreenShotActivity;
import com.swiftcleaner.chovey.view.activity.SimilarPhotosActivity;
import com.swiftcleaner.chovey.view.activity.WhatsAppActivity;
import com.swiftcleaner.chovey.view.dialog.NoticeDialog;
import com.swiftcleaner.chovey.view.function.constellation.XzLoadingActivity;
import com.swiftcleaner.chovey.view.function.weather.WeatherInterface;

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;

    @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();
        } 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 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.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();
//                SharedPreferences.Editor editor = sharedPreferences.edit();
//                editor.putBoolean("isFirstTime", false);
//                editor.apply();
                //加载动画
                binding.startId.setVisibility(View.GONE);
                binding.llAgreement.setVisibility(View.GONE);
                binding.lottieAnimattionView.setVisibility(View.VISIBLE);
                startAnimation();
                CleanApplication.Companion.init();
            }
        });
    }

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

    private void showOpenAd() {
        AdmobManager.INSTANCE.init(this, (ret) -> {
            Log.d("showAppOpenAd","111");
            if (isFinishing() || isDestroyed()) return null;
            if (ret == 0) {
                Log.d("showAppOpenAd","222");
                AdmobManager.INSTANCE.showAppOpenAd(this,
                        () -> {
                            jumpNext("showAppOpenAd 1");
                            Log.d("showAppOpenAd","333");
                            return null;
                        },
                        () -> {
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            Log.d("showAppOpenAd","444");
                            return null;
                        },
                        () -> {
                            jumpNext("showAppOpenAd 2");
                            Log.d("showAppOpenAd","555");
                            return null;
                        }, false
                    );
            } else if (ret == 1) {
                AdmobManager.INSTANCE.showInterstitialAd(this,
                        () -> {
                            jumpNext("showInterstitialAd 1");
                            Log.d("showAppOpenAd","666");
                            return null;
                        },
                        () -> {
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            Log.d("showAppOpenAd","777");
                            return null;
                        },
                        () -> {
                            jumpNext("showInterstitialAd 2");
                            Log.d("showAppOpenAd","888");
                            return null;
                        }, false
                );
            }
            return null;
        }, () -> {
            jumpNext("showAppOpenAd 3");
            Log.d("showAppOpenAd","999");
            return null;
        });
    }
    private void showOpenAdFlase() {
        AdmobManager.INSTANCE.init(this, (ret) -> {
            Log.d("showAppOpenAd","111");
            if (isFinishing() || isDestroyed()) return null;
            if (ret == 0) {
                Log.d("showAppOpenAd","222");
                AdmobManager.INSTANCE.showAppOpenAd(this,
                        () -> {
                            startIntent();
                            Log.d("showAppOpenAd","333");
                            return null;
                        },
                        () -> {
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            Log.d("showAppOpenAd","444");
                            return null;
                        },
                        () -> {
                            startIntent();
                            Log.d("showAppOpenAd","555");
                            return null;
                        }, false
                );
            } else if (ret == 1) {
                AdmobManager.INSTANCE.showInterstitialAd(this,
                        () -> {
                            startIntent();
                            Log.d("showAppOpenAd","666");
                            return null;
                        },
                        () -> {
                            adShowing = true;
                            nonBlockingCountdown.cancel();
                            Log.d("showAppOpenAd","777");
                            return null;
                        },
                        () -> {
                            startIntent();
                            Log.d("showAppOpenAd","888");
                            return null;
                        }, false
                );
            }
            return null;
        }, () -> {
            startIntent();
            Log.d("showAppOpenAd","999");
            return null;
        });
    }
    private void startIntent(){
        startActivity(new Intent(this, GuideActivity.class));
        finish();
    }
    private void setupAgreementTextView() {
        binding.userAgreement.setOnClickListener(v -> {
            Uri uri = Uri.parse("https://sites.google.com/view/terms-swf/terms");
            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(KEY_NOTIFICATION_ID,-1) ;
        Log.e("jumpNext", "actionId=" + actionId);

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

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

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

        if (Objects.equals(actionId, ID_LARGE_FILE_CLEANER)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, LargeFileActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_WHATSAPP)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, WhatsAppActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_APP_PROCESS)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, AppProcessActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_SIMILAR_PHOTOS)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, SimilarPhotosActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_SCREENSHOT_CLEAN)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, ScreenShotActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_WHEATHER)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, WeatherInterface.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, ID_XINGZUO)) {
            AdmobManager.INSTANCE.isShowAdInter();
            startActivity(new Intent(this, XzLoadingActivity.class));
            finish();
            return;
        }
        SharedPreferences preferences = CleanApplication.context.getGuideSharedPreferences();
        boolean isGuideSP = preferences.getBoolean("isGuideSP", false);
        if (isGuideSP){
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }else {
            startActivity(new Intent(this, GuideActivity.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();
        multiplePermissionsLauncher = null;
        notificationSettingsLauncher = null;
    }
}