package com.swiftcleaner.chovey.view.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.databinding.ActivityCleanJunkBinding;
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.view.adapter.ApkCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.EmptyCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.LogsCleanAdapter;
import com.swiftcleaner.chovey.view.adapter.TempCleanAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.zxdemo.admob.AdmobHelper;

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

public class CleanJunkActivity extends AppCompatActivity {
    private ActivityCleanJunkBinding binding;
    private Handler handler;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    List<CleanFileBean> apkFileInfoList;
    List<CleanFileBean> tempFileInfoList;
    List<CleanFileBean> logsFileInfoList;
    ApkCleanAdapter apkCleanAdapter;
    TempCleanAdapter tempCleanAdapter;
    LogsCleanAdapter logsCleanAdapter;
    EmptyCleanAdapter emptyCleanAdapter;
    public long totalSelectedSize = 0;
    private long selectedSize = 0;
    List<CleanFileBean> emptyFiles; // 用于存储空文件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCleanJunkBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initDate();
    }

    private void initDate() {

        binding.emptyFilesRecy.setVisibility(View.GONE);
        binding.apkFilesRecy.setVisibility(View.GONE);
        binding.tempFilesRecy.setVisibility(View.GONE);
        binding.logsFilesRecy.setVisibility(View.GONE);
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.apkFilesAllCl.setOnClickListener(v -> {
            if (binding.apkFilesRecy.getVisibility() == View.VISIBLE) {
                binding.apkFilesRecy.setVisibility(View.GONE);
            } else {
                binding.apkFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.tempFilesAllCl.setOnClickListener(v -> {
            if (binding.tempFilesRecy.getVisibility() == View.VISIBLE) {
                binding.tempFilesRecy.setVisibility(View.GONE);
            } else {
                binding.tempFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.logsFilesAllCl.setOnClickListener(v -> {
            if (binding.logsFilesRecy.getVisibility() == View.VISIBLE) {
                binding.logsFilesRecy.setVisibility(View.GONE);
            } else {
                binding.logsFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.emptyFilesAllCl.setOnClickListener(v -> {
            if (binding.emptyFilesRecy.getVisibility() == View.VISIBLE) {
                binding.emptyFilesRecy.setVisibility(View.GONE);
            } else {
                binding.emptyFilesRecy.setVisibility(View.VISIBLE);
            }
        });
        binding.buttonCleanUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectedSize < 0) {
                    ToastUtil.showLongToast(CleanJunkActivity.this, "请勾选要删除的文件");
                } else {
                    onClickCleanUpButton(view);
                }
            }
        });
        initQueryApkFiles();
        initQueryTempFiles();
        initQueryLogsFiles();
        initQueryEmptyFiles();
    }

    private void initQueryEmptyFiles() {
        emptyFiles = new ArrayList<>();
        executorService.submit(() -> {
            List<CleanFileBean> emptyFolders = FileHelps.findEmptyFolders();

            if (emptyFolders != null) {
                for (CleanFileBean file : emptyFolders) {
                    if (file.getMineType()!=null&&file.getName()!=null){
                        file.setSelected(true); // 设置为选中状态
                        emptyFiles.add(file);
                        totalSelectedSize += file.getLength();
                        selectedSize += file.getLength(); // 更新 selectedSize
                    }
                }
            }
            runOnUiThread(() -> {
                emptyCleanAdapter = new EmptyCleanAdapter(emptyFiles, new EmptyCleanAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateButtonStatus();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateButtonStatus();
                        }
                    }
                });
                binding.emptyFilesRecy.setAdapter(emptyCleanAdapter);
                binding.emptyFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
            });
        });
    }

    private void initQueryApkFiles() {
        apkFileInfoList = new ArrayList<>();
        emptyFiles = new ArrayList<>();
        executorService.submit(() -> {
            List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
            if (specifiedFiles != null) {
                for (CleanFileBean file : specifiedFiles) {
                    if ((file.getMineType() != null && (file.getMineType().endsWith(".apk") || file.getMineType().endsWith(".APK"))) ||
                            (file.getName() != null && file.getName().toLowerCase().endsWith(".apk"))) {
                        if (file.getLength() == 0) {
                            file.setSelected(true); // 设置为选中状态
                            emptyFiles.add(file);
                        } else {
                            file.setSelected(true); // 设置为选中状态
                            apkFileInfoList.add(file);
                            totalSelectedSize += file.getLength();
                            selectedSize += file.getLength(); // 更新 selectedSize
                        }
                    }
                }
            }
            runOnUiThread(() -> {
                apkCleanAdapter = new ApkCleanAdapter(apkFileInfoList, new ApkCleanAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateButtonStatus();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateButtonStatus();
                        }
                    }
                });
                binding.apkFilesRecy.setAdapter(apkCleanAdapter);
                binding.apkFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
            });
        });
    }

    private void initQueryTempFiles() {
        tempFileInfoList = new ArrayList<>();
        emptyFiles = new ArrayList<>();
        executorService.submit(() -> {
            List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
            if (specifiedFiles != null) {
                for (CleanFileBean file : specifiedFiles) {
                    if ((file.getMineType() != null && (file.getMineType().endsWith(".temp") || file.getMineType().endsWith(".TEMP"))) ||
                            (file.getName() != null && file.getName().toLowerCase().endsWith(".temp"))) {
                        if (file.getLength() == 0) {
                            file.setSelected(true); // 设置为选中状态
                            emptyFiles.add(file);
                        } else {
                            file.setSelected(true); // 设置为选中状态
                            tempFileInfoList.add(file);
                            totalSelectedSize += file.getLength();
                            selectedSize += file.getLength(); // 更新 selectedSize
                        }
                    }
                }
            }
            runOnUiThread(() -> {
                tempCleanAdapter = new TempCleanAdapter(tempFileInfoList, new TempCleanAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateButtonStatus();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateButtonStatus();
                        }
                    }
                });
                binding.tempFilesRecy.setAdapter(tempCleanAdapter);
                binding.tempFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
            });
        });
    }

    private void initQueryLogsFiles() {
        logsFileInfoList = new ArrayList<>();
        emptyFiles = new ArrayList<>();
        executorService.submit(() -> {
            List<CleanFileBean> specifiedFiles = MediaHelps.findSpecifiedFiles(this);
            if (specifiedFiles != null) {
                for (CleanFileBean file : specifiedFiles) {
                    if ((file.getMineType() != null && (file.getMineType().endsWith(".log") || file.getMineType().endsWith(".LOG"))) ||
                            (file.getName() != null && file.getName().toLowerCase().endsWith(".log"))) {
                        if (file.getLength() == 0) {
                            file.setSelected(true); // 设置为选中状态
                            emptyFiles.add(file);
                        } else {
                            file.setSelected(true); // 设置为选中状态
                            logsFileInfoList.add(file);
                            totalSelectedSize += file.getLength();
                            selectedSize += file.getLength(); // 更新 selectedSize
                        }
                    }
                }
            }
            runOnUiThread(() -> {
                logsCleanAdapter = new LogsCleanAdapter(logsFileInfoList, new LogsCleanAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateButtonStatus();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateButtonStatus();
                        }
                    }
                });
                binding.logsFilesRecy.setAdapter(logsCleanAdapter);
                binding.logsFilesRecy.setLayoutManager(new LinearLayoutManager(this));
                binding.wasteNumber.setText(formatFileSize(totalSelectedSize));
            });
        });
    }

    private void updateButtonStatus() {
        binding.buttonCleanUp.setText("Clean Up " + formatFileSize(selectedSize));
//        if (selectedSize == 0) {
//            binding.buttonCleanUp.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_radio_80dp_hui_se));
//        } else {
//            binding.buttonCleanUp.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_clean_up));
//        }
    }

    //apk 删除
    public void apkCleanFiles(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);
                apkCleanAdapter.removeSelectedFiles(selectedFiles);
                apkCleanAdapter.notifyDataSetChanged();

            });
        });
    }

    //temp 删除
    public void tempCleanFiles(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);
                tempCleanAdapter.removeSelectedFiles(selectedFiles);
                tempCleanAdapter.notifyDataSetChanged();

            });
        });
    }

    //logs 删除
    public void logsCleanFiles(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);
                logsCleanAdapter.removeSelectedFiles(selectedFiles);
                logsCleanAdapter.notifyDataSetChanged();

            });
        });
    }

    //empty 删除
    public void emptyCleanFiles(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);
                emptyCleanAdapter.removeSelectedFiles(selectedFiles);
                emptyCleanAdapter.notifyDataSetChanged();
            });
        });
    }

    public void onClickCleanUpButton(View view) {
        List<CleanFileBean> apkSelectedFiles = apkCleanAdapter.getSelectedFiles();
        List<CleanFileBean> tempSelectedFiles = tempCleanAdapter.getSelectedFiles();
        List<CleanFileBean> logsSelectedFiles = logsCleanAdapter.getSelectedFiles();
        List<CleanFileBean> emptySelectedFiles = emptyCleanAdapter.getSelectedFiles();
        apkCleanFiles(apkSelectedFiles);
        tempCleanFiles(tempSelectedFiles);
        logsCleanFiles(logsSelectedFiles);
        emptyCleanFiles(emptySelectedFiles);
        selectedSize = 0;
        updateButtonStatus();
        initAnimation(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];
    }

    private void initAnimation(String str) {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.clLayout.setVisibility(View.GONE);
        binding.radarview.setSearching(true);
        handler = new Handler();
        Intent intent = new Intent(this, EndCleanJunkActivity.class);
        handler.postDelayed(() -> {
            binding.radarview.setSearching(false);
            intent.putExtra("cleanstr", str);
            startActivity(intent);
            finish();
        }, 3000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.radarview != null) {
            binding.radarview.setSearching(false);
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        executorService.shutdown();
    }

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

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

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

            @Override
            public void onSubmit() {
                AdmobHelper.INSTANCE.showInterstitialAd(CleanJunkActivity.this, () -> {
                            finish();
                            return null;
                        },
                        () -> {
                            return null;
                        },
                        () -> {
                            finish();
                            return null;
                        });
            }
        });
        customScoreDialog.show();
    }
}