package com.swiftcleaner.chovey.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.business.EventUtils;
import com.swiftcleaner.chovey.business.admob.AdmobManager;
import com.swiftcleaner.chovey.databinding.ActivityLargeFileBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.tool.FileHelps;
import com.swiftcleaner.chovey.model.tool.MediaHelps;
import com.swiftcleaner.chovey.model.tool.ToastUtil;
import com.swiftcleaner.chovey.model.util.FinishMain;
import com.swiftcleaner.chovey.view.BaseActivity;
import com.swiftcleaner.chovey.view.BaseActivityKotlin;
import com.swiftcleaner.chovey.view.MainActivity;
import com.swiftcleaner.chovey.view.adapter.LargeFileAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.swiftcleaner.chovey.view.dialog.LoadingDialog;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LargeFileActivity extends BaseActivity<ActivityLargeFileBinding> {

    private LargeFileAdapter largeFileAdapter;
    private Set<CleanFileBean> allFiles; // 使用Set减少内存开销
    private CountDownTimer countDownTimer;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private long selectedSize = 0;
    private ValueAnimator animator;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 101;

    @Override
    protected ActivityLargeFileBinding getViewBinding() {
        return ActivityLargeFileBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initBar();
    }

    @Override
    protected void initData() {
        EventUtils.INSTANCE.event("page_LargeFileActivity", "", null);
        initPage();
        initTypeFile();
        initShow();
    }

    private void initPage() {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.radarview.setSearching(true);
        AdmobManager.INSTANCE.showNativeAd(LargeFileActivity.this, (nativeAd) -> {
            binding.flAdDonghua.removeAllViews();
            binding.flAdDonghua.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
        initAnimotorPer();
        countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                binding.radarview.setSearching(false);
                countDownTimer.cancel();
                animator.cancel();
                binding.clRadarview.setVisibility(View.GONE);
                LoadingDialog loadingDialog = new LoadingDialog(LargeFileActivity.this);
                loadingDialog.show();
                if (AdmobManager.INSTANCE.isShowAdInter()) {
                    AdmobManager.INSTANCE.showInterstitialAd(LargeFileActivity.this, () -> {
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            }, false);
                } else {
                    checkAndRequestPermissions();
                    loadingDialog.dismiss();
                }
            }
        }.start();
        AdmobManager.INSTANCE.showNativeAd(LargeFileActivity.this, (nativeAd) -> {
            binding.flAd.removeAllViews();
            binding.flAd.setNativeAd(nativeAd, R.layout.layout_ad_native);
            return null;
        }, null, null);
    }

    private void checkAndRequestPermissions() {
        if (!checkFilesAccessPermission(this)) {
            // 没有权限，请求权限
            requestFilesAccessPermission();
        }
    }

    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
    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
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以继续操作
            } else {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    private void initShow() {
        binding.ivReturn.setOnClickListener(v -> initCustDialog());
        binding.largeFileButton.setOnClickListener(v -> {
            if (selectedSize == 0) {
                ToastUtil.showLongToast(this, "Please check the file to be deleted");
            } else {
                showCustomDialog();
            }
        });

    }

    //查询文件
    private void initTypeFile() {
        executorService.submit(() -> {
            allFiles = new HashSet<>();

            allFiles.addAll(MediaHelps.findFiles(this, 10 * 1024 * 1024));
            runOnUiThread(this::updateUI);
        });
    }

    private void updateUI() {
        largeFileAdapter = new LargeFileAdapter(new ArrayList<>(allFiles), fileBean -> {
            if (fileBean.isSelected()) {
                selectedSize += fileBean.getLength();
            } else {
                selectedSize -= fileBean.getLength();
            }
            updateDeleteButton();
        });
        binding.largeFileRecy.setAdapter(largeFileAdapter);
        binding.largeFileRecy.setLayoutManager(new LinearLayoutManager(this));
        binding.tvLoad.setVisibility(View.GONE);
    }

    private void updateDeleteButton() {
        binding.largeFileButton.setText("Delete " + formatFileSize(selectedSize));
        binding.largeFileButton.setBackground(selectedSize == 0 ? ContextCompat.getDrawable(this, R.drawable.shape_radio_80dp_hui_se) : ContextCompat.getDrawable(this, R.drawable.shape_clean_up));
    }

    private static String formatFileSize(long size) {
        if (size <= 0) return "0 Bytes";
        final String[] units = new String[]{"Bytes", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    private void showCustomDialog() {
        Dialog dialog = new Dialog(this, R.style.TransparentDialogTheme);
        dialog.setContentView(R.layout.dialog_delete);

        AppCompatButton dialog_delete_cancel = dialog.findViewById(R.id.dialog_delete_cancel);
        AppCompatButton dialog_delete_ok = dialog.findViewById(R.id.dialog_delete_ok);

        CardView cardview = dialog.findViewById(R.id.cardview);
        cardview.setCardBackgroundColor(Color.TRANSPARENT);
        dialog_delete_cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
        dialog_delete_ok.setOnClickListener(v -> {
            List<CleanFileBean> selectedFiles = largeFileAdapter.getSelectedFiles();
            cleanFiles(selectedFiles);
            dialog.dismiss();
            //跳转
            initAnimation(formatFileSize(selectedSize));
        });

        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private void cleanFiles(List<CleanFileBean> selectedFiles) {
        executorService.submit(() -> {
            // 在后台线程中执行文件删除操作
            for (CleanFileBean selectedFile : selectedFiles) {
                FileHelps.deleteFile(selectedFile.getPath());
            }

            // 在主线程中更新媒体库
            runOnUiThread(() -> {
                String[] paths = selectedFiles.stream()
                        .map(CleanFileBean::getPath)
                        .toArray(String[]::new);
                MediaHelps.updateMedia(getApplication(), paths);
                largeFileAdapter.removeSelectedFiles(selectedFiles);
                largeFileAdapter.notifyDataSetChanged();
                selectedSize = 0;
                updateDeleteButton();
            });
        });
    }

    private void initAnimotorPer() {
        // 创建ValueAnimator，从1到100
        animator = ValueAnimator.ofInt(1, 100);
        animator.setDuration(5000); // 3秒

        // 设置更新监听器，每帧更新进度文本
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (int) animation.getAnimatedValue();
                binding.parText.setText(currentValue + "%");
            }
        });
        // 开始动画
        animator.start();
    }

    private void initAnimation(String str) {
        Intent intent = new Intent(this, EndCleanJunkActivity.class);
        intent.putExtra("cleanstr", str);
        startActivity(intent);
        finish();
    }

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

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        initCustDialog();
    }

    private void initCustDialog() {
        Activity activity = this;
        CustomScoreDialog customScoreDialog = new CustomScoreDialog(this);
        customScoreDialog.setOnDialogClickListener(new CustomScoreDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                customScoreDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                if (AdmobManager.INSTANCE.isShowAdBackInter()){
                    AdmobManager.INSTANCE.showInterstitialAd(LargeFileActivity.this, () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                return null;
                            },
                            () -> {
                                return null;
                            },
                            () -> {
                                FinishMain.INSTANCE.finishToMain(activity);
                                return null;
                            }, false);
                }else {
                    finish();
                }

            }
        });
        customScoreDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        executorService.shutdownNow(); // 使用shutdownNow确保线程池立即停止
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (animator != null) {
            animator.cancel();
        }
    }
}
