package com.swiftcleaner.chovey.view.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.databinding.ActivityLargeFileBinding;
import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.bean.DialogLargeFileBean;
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.LargeFileAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;

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

public class LargeFileActivity extends AppCompatActivity {
    private ActivityLargeFileBinding binding;
    private DialogLargeFileBean bean;
    private LargeFileAdapter largeFileAdapter;
    private List<CleanFileBean> allFiles;
    private Handler handler;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private long selectedSize = 0;

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

    private void initShow() {
        bean = new DialogLargeFileBean();
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.largeFileButton.setOnClickListener(v -> {
            if (selectedSize == 0) {
                ToastUtil.showLongToast(this, "请勾选要删除的文件");
            } else {
                showCustomDialog();
            }
        });
        initTypeFile();
    }

    private void initTypeFile() {
        executorService.submit(() -> {
            allFiles = new ArrayList<>();
            // 获取图片文件
            List<CleanFileBean> imageFiles = MediaHelps.findImageFiles(LargeFileActivity.this, 0);
            filterAndAddLargeFiles(imageFiles, allFiles);

            // 获取视频文件
            List<CleanFileBean> videoFiles = MediaHelps.findVideoFiles(LargeFileActivity.this, 0);
            filterAndAddLargeFiles(videoFiles, allFiles);

            // 获取音频文件
            List<CleanFileBean> audioFiles = MediaHelps.findAudioFiles(LargeFileActivity.this, 0);
            filterAndAddLargeFiles(audioFiles, allFiles);

            // 获取文档文件
            List<CleanFileBean> docFiles = MediaHelps.findDocFiles(LargeFileActivity.this, 0);
            filterAndAddLargeFiles(docFiles, allFiles);

            // 获取 APK 文件
            List<CleanFileBean> apkFiles = MediaHelps.findSpecifiedFiles(LargeFileActivity.this);
            filterAndAddLargeFiles(apkFiles, allFiles);

            // 获取其他文件并筛选大文件
            String externalPath = Environment.getExternalStorageDirectory().getPath();
            File externalDir = new File(externalPath);
            if (externalDir.exists() && externalDir.isDirectory()) {
                File[] files = externalDir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (!isImageFile(file) && !isVideoFile(file) && !isAudioFile(file) && !isDocFile(file) && !isApkFile(file)) {
                            if (file.length() > 10 * 1024 * 1024) {
                                CleanFileBean otherFile = new CleanFileBean(file.getName(), file.getPath(), null, file.length(), file.lastModified(), null);
                                allFiles.add(otherFile);
                            }
                        }
                    }
                }
            }

            // 更新 UI
            runOnUiThread(() -> {
                largeFileAdapter = new LargeFileAdapter(allFiles, new LargeFileAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(CleanFileBean fileBean) {
                        if (fileBean.isSelected()) {
                            selectedSize += fileBean.getLength();
                            updateDeleteButton();
                        } else {
                            selectedSize -= fileBean.getLength();
                            updateDeleteButton();
                        }
                    }
                });
                binding.largeFileRecy.setAdapter(largeFileAdapter);
                binding.largeFileRecy.setLayoutManager(new LinearLayoutManager(LargeFileActivity.this));
            });
        });
    }

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

    private void filterAndAddLargeFiles(List<CleanFileBean> sourceFiles, List<CleanFileBean> targetList) {
        for (CleanFileBean file : sourceFiles) {
            if (file.getLength() > 10 * 1024 * 1024) {
                targetList.add(file);
            }
        }
    }

    private boolean isImageFile(File file) {
        if (file == null) {
            return false;
        }
        String fileName = file.getName();
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") ||
                fileName.endsWith(".gif") || fileName.endsWith(".bmp") || fileName.endsWith(".tiff") ||
                fileName.endsWith(".webp"); // 添加更多图片后缀
    }

    private boolean isVideoFile(File file) {
        if (file == null) {
            return false;
        }
        String fileName = file.getName();
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".mp4") || fileName.endsWith(".avi") || fileName.endsWith(".mkv") ||
                fileName.endsWith(".mov") || fileName.endsWith(".wmv") || fileName.endsWith(".flv") ||
                fileName.endsWith(".mpg") || fileName.endsWith(".mpeg"); // 添加更多视频后缀
    }

    private boolean isAudioFile(File file) {
        if (file == null) {
            return false;
        }
        String fileName = file.getName();
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".mp3") || fileName.endsWith(".wav") || fileName.endsWith(".aac")
                || fileName.endsWith(".ogg") || fileName.endsWith(".wma"); // 添加更多音频后缀
    }

    private boolean isDocFile(File file) {
        if (file == null) {
            return false;
        }
        String fileName = file.getName();
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".pdf") ||
                fileName.endsWith(".xls") || fileName.endsWith(".xlsx") || fileName.endsWith(".ppt") ||
                fileName.endsWith(".pptx") || fileName.endsWith(".txt"); // 添加更多文档后缀
    }

    private boolean isApkFile(File file) {
        if (file == null) {
            return false;
        }
        String fileName = file.getName();
        if (fileName == null) {
            return false;
        }
        return fileName.endsWith(".apk");
    }

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

    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() {
                customScoreDialog.dismiss();
                finish();
            }
        });
        customScoreDialog.show();
    }

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

}