package com.swiftcleaner.chovey.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
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.ActivityWhatsAppBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.tool.FileHelps;
import com.swiftcleaner.chovey.model.tool.FileTypes;
import com.swiftcleaner.chovey.model.tool.MediaHelps;
import com.swiftcleaner.chovey.model.tool.ToastUtil;
import com.swiftcleaner.chovey.model.util.AppSchedulers;
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.WhatsAppCleanAudioAdapter;
import com.swiftcleaner.chovey.view.adapter.WhatsAppCleanImageAdapter;
import com.swiftcleaner.chovey.view.adapter.WhatsAppCleanVideoAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.swiftcleaner.chovey.view.dialog.LoadingDialog;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

public class WhatsAppActivity extends BaseActivity<ActivityWhatsAppBinding> {
    private static final int REQUEST_CODE = 1;
    WhatsAppCleanImageAdapter appCleanImageAdapter;
    WhatsAppCleanAudioAdapter appCleanAudioAdapter;
    WhatsAppCleanVideoAdapter appCleanVideoAdapter;

    private long totalSelectedSize = 0;
    private long selectedSize = 0;
    List<CleanFileBean> videoList;
    List<CleanFileBean> imageList;
    List<CleanFileBean> audioList;
    List<CleanFileBean> files;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ValueAnimator animator;
    private CountDownTimer countDownTimer;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 101;

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

    @Override
    protected void initView() {
        initBar();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }

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

    private void initPage() {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.radarview.setSearching(true);
        AdmobManager.INSTANCE.showNativeAd(WhatsAppActivity.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(WhatsAppActivity.this);
                loadingDialog.show();
                if (AdmobManager.INSTANCE.isShowAdInter()) {
                    AdmobManager.INSTANCE.showInterstitialAd(WhatsAppActivity.this, () -> {
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            },
                            () -> {
                                checkAndRequestPermissions();
                                loadingDialog.dismiss();
                                binding.flAdDonghua.removeAllViews();
                                return null;
                            }, false);
                } else {
                    checkAndRequestPermissions();
                    loadingDialog.dismiss();
                    binding.flAdDonghua.removeAllViews();
                }
            }
        }.start();
        AdmobManager.INSTANCE.showNativeAd(WhatsAppActivity.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.imageFilesRecy.setVisibility(View.VISIBLE);
        binding.videoFilesRecy.setVisibility(View.VISIBLE);
        binding.audioFilesRecy.setVisibility(View.VISIBLE);

        binding.imageFilesAllCl.setOnClickListener(v -> {
            if (binding.imageFilesRecy.getVisibility() == View.VISIBLE) {
                binding.imageFilesRecy.setVisibility(View.GONE);
            } else {
                binding.imageFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.videoFilesAllCl.setOnClickListener(v -> {
            if (binding.videoFilesRecy.getVisibility() == View.VISIBLE) {
                binding.videoFilesRecy.setVisibility(View.GONE);
            } else {
                binding.videoFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.audioFilesAllCl.setOnClickListener(v -> {
            if (binding.audioFilesRecy.getVisibility() == View.VISIBLE) {
                binding.audioFilesRecy.setVisibility(View.GONE);
            } else {
                binding.audioFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.buttonCleanUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectedSize < 0) {
                    ToastUtil.showLongToast(WhatsAppActivity.this, "Please check the file to be deleted");
                } else {
                    if (view != null) {
                        onClickCleanUpButton(view);
                    }
                }
            }
        });
        initImage();
        initVideo();
        initAudio();
        compositeDisposable.add(initImage().andThen(initAudio()).andThen(initVideo()).subscribe(() -> {
            // 所有操作完成后执行
            binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
        }, throwable -> {
            // 处理错误
            throwable.printStackTrace();
        }));
    }


    public void onClickCleanUpButton(View view) {
        List<CleanFileBean> imageFiles;
        List<CleanFileBean> videoFiles;
        List<CleanFileBean> audioFiles;
        if (appCleanImageAdapter != null) {
            imageFiles = appCleanImageAdapter.getSelectedFiles();
            ImageCleanFiles(imageFiles);
        }
        if (appCleanVideoAdapter != null) {
            videoFiles = appCleanVideoAdapter.getSelectedFiles();
            VideoCleanFiles(videoFiles);
        }
        if (appCleanVideoAdapter != null) {
            audioFiles = appCleanAudioAdapter.getSelectedFiles();
            AudioCleanFiles(audioFiles);
        }

        updateButtonStatus();
        //跳转页面
        initAnimation(formatFileSize(selectedSize));
    }

    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();
    }

    //图片删除
    public void ImageCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    appCleanImageAdapter.removeSelectedFiles(selectedFiles);
                    appCleanImageAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    //视频删除
    public void VideoCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    appCleanVideoAdapter.removeSelectedFiles(selectedFiles);
                    appCleanVideoAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    //音频删除
    public void AudioCleanFiles(List<CleanFileBean> selectedFiles) {
        Disposable disposable = Observable.fromCallable(() -> {
                    // 文件删除操作，放到后台线程执行
                    for (CleanFileBean selectedFile : selectedFiles) {
                        FileHelps.deleteFile(selectedFile.getPath());
                    }

                    // 将删除的文件路径转换为数组
                    String[] paths = selectedFiles.stream()
                            .map(CleanFileBean::getPath)
                            .toArray(String[]::new);
                    return paths;
                })
                .subscribeOn(AppSchedulers.io()) // 在后台线程执行文件删除
                .observeOn(AppSchedulers.mainThread()) // 切换到主线程执行 UI 更新
                .subscribe(paths -> {
                    // 更新媒体库
                    MediaHelps.updateMedia(getApplication(), paths);
                    appCleanAudioAdapter.removeSelectedFiles(selectedFiles);
                    appCleanAudioAdapter.notifyDataSetChanged();
                }, throwable -> {
                    // 处理错误
                    throwable.printStackTrace();
                });
        compositeDisposable.add(disposable);
    }

    private Completable initImage() {
        return Completable.fromObservable(Observable.fromCallable(() -> {
                            files = FileHelps.findWhatsappFiles();
                            Log.d("ssad", files.toString());
                            if (files != null) {
                                imageList = files.stream()
                                        .filter(file -> FileTypes.images.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                                        .collect(Collectors.toList());
                            }
                            return imageList;
                        }).subscribeOn(AppSchedulers.io())
                        .observeOn(AppSchedulers.mainThread())
                        .doOnNext(emptyFolders -> {
                            long totalSize = imageList.stream()
                                    .mapToLong(CleanFileBean::getLength)
                                    .sum();
                            totalSelectedSize += totalSize;
                            appCleanImageAdapter = new WhatsAppCleanImageAdapter(imageList, new WhatsAppCleanImageAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(CleanFileBean fileBean) {
                                    if (fileBean.isSelected()) {
                                        selectedSize += fileBean.getLength();
                                        updateButtonStatus();
                                    } else {
                                        selectedSize -= fileBean.getLength();
                                        updateButtonStatus();
                                    }
                                }
                            });
                            binding.imageFilesRecy.setAdapter(appCleanImageAdapter);
                            binding.imageFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                        }))
                .onErrorComplete();
    }

    private Completable initAudio() {
        return Completable.fromObservable(Observable.fromCallable(() -> {
                            files = FileHelps.findWhatsappFiles();
                            Log.d("ssad", files.toString());
                            if (files != null) {
                                audioList = files.stream()
                                        .filter(file -> FileTypes.audios.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                                        .collect(Collectors.toList());
                            }
                            return audioList;
                        }).subscribeOn(AppSchedulers.io())
                        .observeOn(AppSchedulers.mainThread())
                        .doOnNext(emptyFolders -> {
                            long totalSize = audioList.stream()
                                    .mapToLong(CleanFileBean::getLength)
                                    .sum();
                            totalSelectedSize += totalSize;
                            appCleanAudioAdapter = new WhatsAppCleanAudioAdapter(audioList, new WhatsAppCleanAudioAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(CleanFileBean fileBean) {
                                    if (fileBean.isSelected()) {
                                        selectedSize += fileBean.getLength();
                                        updateButtonStatus();
                                    } else {
                                        selectedSize -= fileBean.getLength();
                                        updateButtonStatus();
                                    }
                                }
                            });
                            binding.audioFilesRecy.setAdapter(appCleanAudioAdapter);
                            binding.audioFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                        }))
                .onErrorComplete();
    }

    private Completable initVideo() {
        return Completable.fromObservable(Observable.fromCallable(() -> {
                            files = FileHelps.findWhatsappFiles();
                            Log.d("ssad", files.toString());
                            if (files != null) {
                                videoList = files.stream()
                                        .filter(file -> FileTypes.videos.stream().anyMatch(suffix -> file.getName().toLowerCase(Locale.ROOT).endsWith(suffix)))
                                        .collect(Collectors.toList());
                            }
                            return videoList;
                        }).subscribeOn(AppSchedulers.io())
                        .observeOn(AppSchedulers.mainThread())
                        .doOnNext(emptyFolders -> {
                            long totalSize = videoList.stream()
                                    .mapToLong(CleanFileBean::getLength)
                                    .sum();
                            totalSelectedSize += totalSize;
                            appCleanVideoAdapter = new WhatsAppCleanVideoAdapter(videoList, new WhatsAppCleanVideoAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(CleanFileBean fileBean) {
                                    if (fileBean.isSelected()) {
                                        selectedSize += fileBean.getLength();
                                        updateButtonStatus();
                                    } else {
                                        selectedSize -= fileBean.getLength();
                                        updateButtonStatus();
                                    }
                                }
                            });
                            binding.videoFilesRecy.setAdapter(appCleanVideoAdapter);
                            binding.videoFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                        }))
                .onErrorComplete();
    }

    private void updateButtonStatus() {
        binding.buttonCleanUp.setText("Clean Up " + formatFileSize(selectedSize));
    }

    private 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];
    }

    @Override
    public void onBackPressed() {
        initCustDialog();
    }

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

    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(WhatsAppActivity.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();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (animator != null) {
            animator.cancel();
        }
        compositeDisposable.clear();
        if (compositeDisposable != null) {
            compositeDisposable.dispose(); // 取消所有订阅
        }
    }
}