package com.swiftcleaner.chovey.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
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.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.CleanApplication;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.databinding.ActivityGuideBinding;
import com.swiftcleaner.chovey.view.MainActivity;
import com.swiftcleaner.chovey.view.adapter.ViewPagerAdapter;

public class GuideActivity extends AppCompatActivity {
    private ViewPagerAdapter adapter;
    ActivityGuideBinding binding;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 101;
    private SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGuideBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        preferences = CleanApplication.context.getGuideSharedPreferences();
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setPagingEnabled(false);
        binding.viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 页面切换时处理逻辑
            }
        });

    }

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

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("showNativeAd","111");
        AdmobManager.INSTANCE.showNativeAd(this, (nativeAd) -> {
            binding.guideAd.removeAllViews();
            Log.d("showNativeAd","222");
            binding.guideAd.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
    }

    public void nextPage() {
        if (adapter == null || adapter.getCount() == 0) {
            Toast.makeText(this, "No pages available", Toast.LENGTH_SHORT).show();
            return;
        }

        int currentPosition = binding.viewPager.getCurrentItem();
        if (currentPosition < adapter.getCount() - 1) {
            binding.viewPager.setCurrentItem(currentPosition + 1, true);
        } else {
            if (AdmobManager.INSTANCE.isShowAdInterGuide()){
                AdmobManager.INSTANCE.showInterstitialAd(this,
                        () -> {
                            startIntent();
                            checkAndRequestPermissions();
                            Log.d("isShowAdInterGuide","Ad loading failed");
                            return null;
                        },
                        () -> {
                            Log.d("isShowAdInterGuide","Advertisement loaded successfully");
                            return null;
                        },
                        () -> {
                            Log.d("isShowAdInterGuide","Ad loading ends");
                            startIntent();
                            checkAndRequestPermissions();
                            return null;
                        }, false);
            }else {
                startIntent();
                checkAndRequestPermissions();
                Log.d("isShowAdInterGuide",AdmobManager.INSTANCE.isShowAdInterGuide()+"Close Advertisement");
            }
        }
    }
    private void startIntent() {
        startActivity(new Intent(GuideActivity.this, CollectActivity.class));
        finish();  // 关闭当前的 GuideActivity
    }

    private void checkAndRequestPermissions() {
        if (!checkFilesAccessPermission(this)) {
            // 没有权限，请求权限
            requestFilesAccessPermission();
            SharedPreferences.Editor edit = preferences.edit();
            edit.putBoolean("isGuideSP",true);
            edit.commit();
        }
    }

    private boolean checkFilesAccessPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else {
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Unable to request permission, please grant manually", Toast.LENGTH_SHORT).show();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION || requestCode == REQUEST_PERMISSION_CODE) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // 权限未授予，提示用户
                    Toast.makeText(this, "Permission not granted, please grant manually", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.viewPager != null) {
            binding.viewPager.clearOnPageChangeListeners();
        }
    }
}