package com.swiftcleaner.chovey.view.activity;

import static com.swiftcleaner.chovey.model.bean.Global.FUNCTION_APP_MANAGER;
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 androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.animation.Animator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.databinding.ActivityStartBinding;
import com.swiftcleaner.chovey.model.util.PermissionUtils;
import com.swiftcleaner.chovey.view.MainActivity;
import com.zxdemo.admob.AdmobHelper;
import com.zxdemo.utils.NonBlockingCountdown;

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 = 15;
    public AtomicBoolean jumped = new AtomicBoolean(false);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStartBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initPermission();
        sharedPreferences = getSharedPreferences("AppPreferences", MODE_PRIVATE);

        boolean isFirstTime = sharedPreferences.getBoolean("isFirstTime", true);

        showOpenAd();
        if (!isFirstTime) {
            //点击过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) {
            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) {
            PermissionUtils.requestNotificationPermission(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) {
                showOpenAd();
                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();
            }
        });
    }

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

    private void showOpenAd() {
        AdmobHelper.INSTANCE.showAppOpenAd(this,
                () -> {
                    jumpNext();
                    return null;
                },
                () -> {
                    adShowing = true;
                    nonBlockingCountdown.cancel();
                    return null;
                },
                () -> {
                    jumpNext();
                    return null;
                }

        );
    }

    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);
            startActivity(intent);
        });
        binding.privacyPolicy.setOnClickListener(v -> {
            Uri uri = Uri.parse("https://sites.google.com/view/swift-cleaner/swift-clean");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("jumpNext", "onNewIntent jumped=" + jumped.get());
        jumpNext();
    }

    private void jumpNext() {
        Log.e("jumpNext", "jumped=" + jumped.get());
        if (jumped.get()) return;
        jumped.set(true);
        String actionId = getIntent().getExtras() != null ? getIntent().getExtras().getString("actionId") : "";
        Log.e("jumpNext", "actionId=" + actionId);

        if (Objects.equals(actionId, FUNCTION_CLEAN)) {
            startActivity(new Intent(this, CleanJunkActivity.class));
            finish();
            return;
        }

        if (Objects.equals(actionId, FUNCTION_APP_MANAGER)) {
            startActivity(new Intent(this, BatteryInfoActivity.class));
            finish();
            return;
        }
        if (Objects.equals(actionId, FUNCTION_BATTERY)) {
            startActivity(new Intent(this, InfoActivity.class));
            finish();
            return;
        }

        if (Objects.equals(actionId, FUNCTION_LARGE_FILE)) {
            startActivity(new Intent(this, LargeFileActivity.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(); // 销毁缓存
        }
    }
}