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.GridLayoutManager;

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

import com.gyf.immersionbar.ImmersionBar;
import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.databinding.ActivityScreenShotBinding;
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.activity.EndCleanJunkActivity;
import com.swiftcleaner.chovey.view.adapter.ScreenShotAdapter;
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog;
import com.zxdemo.admob.AdmobHelper;
import com.zxdemo.http.ZxHttp;

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

public class ScreenShotActivity extends AppCompatActivity {
    private ActivityScreenShotBinding binding;
    private ScreenShotAdapter screenShotAdapter;
    private List<CleanFileBean> cleanFileBeans;
    private Handler handler;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private long wasteNumber = 0;
    private long selectedSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityScreenShotBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ZxHttp.INSTANCE.getHttpReportInterface("page_ScreenShotActivity", "", null);
        initBar();
        initShow();
    }

    private void initShow() {
        binding.ivReturn.setOnClickListener(v -> {
            initCustDialog();
        });
        binding.buttonScreenshotDelete.setOnClickListener(v -> {
            if (selectedSize == 0) {
                ToastUtil.showLongToast(this, "请勾选要删除的文件");
            } else {
                showCustomDialog();
            }
        });
        executorService.submit(() -> {
            Map<String, List<CleanFileBean>> screenshotsMap = MediaHelps.findScreenshotsFiles(this);
            cleanFileBeans = new ArrayList<>(screenshotsMap.values().size());

            for (List<CleanFileBean> files : screenshotsMap.values()) {
                for (CleanFileBean file : files) {
                    cleanFileBeans.add(file);
                    wasteNumber += file.getLength();
                }
            }

            runOnUiThread(() -> {
                binding.tvLoad.setVisibility(View.GONE);
                screenShotAdapter = new ScreenShotAdapter(cleanFileBeans, (fileBean) -> {
                    if (fileBean.isSelected()) {
                        selectedSize += fileBean.getLength();
                        updateDeleteButton();
                    } else {
                        selectedSize -= fileBean.getLength();
                        updateDeleteButton();
                    }
                });
                binding.screenshotRecy.setLayoutManager(new GridLayoutManager(this, 3));
                binding.screenshotRecy.setAdapter(screenShotAdapter);
                binding.wasteNumber.setText(formatFileSize(wasteNumber));
            });
        });
    }

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

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

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

        CardView cardView = dialog.findViewById(R.id.cardview);
        cardView.setCardBackgroundColor(Color.TRANSPARENT);

        dialogDeleteCancel.setOnClickListener(v -> dialog.dismiss());
        dialogDeleteOk.setOnClickListener(v -> {
            List<CleanFileBean> selectedFiles = screenShotAdapter.getSelectedFiles();
            cleanFiles(selectedFiles);
            dialog.dismiss();
            initAnimation(formatFileSize(selectedSize));
        });

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

    private void cleanFiles(List<CleanFileBean> selectedFiles) {
        executorService.submit(() -> {
            for (CleanFileBean fileBean : selectedFiles) {
                FileHelps.deleteFile(fileBean.getPath());
            }

            runOnUiThread(() -> {
                String[] paths = selectedFiles.stream()
                        .map(CleanFileBean::getPath)
                        .toArray(String[]::new);
                MediaHelps.updateMedia(getApplication(), paths);
                screenShotAdapter.removeSelectedFiles(selectedFiles);
                screenShotAdapter.notifyDataSetChanged();
                selectedSize = 0;
                updateDeleteButton();
            });
        });
    }

    private void initAnimation(String cleanSize) {
        binding.clRadarview.setVisibility(View.VISIBLE);
        binding.clLayout.setVisibility(View.GONE);
        binding.radarview.setSearching(true);

        handler = new Handler(Looper.getMainLooper());
        Intent intent = new Intent(this, EndCleanJunkActivity.class);
        handler.postDelayed(() -> {
            AdmobHelper.INSTANCE.showAppOpenAd(this,
                    () -> {
                        binding.radarview.setSearching(false);
                        intent.putExtra("cleanstr", cleanSize);
                        startActivity(intent);
                        finish();
                        return null;
                    },
                    () -> {

                        return null;
                    },
                    () -> {
                        binding.radarview.setSearching(false);
                        intent.putExtra("cleanstr", cleanSize);
                        startActivity(intent);
                        finish();
                        return null;
                    }
            );
        }, 3000);
//        handler.postDelayed(() -> {
//            binding.radarview.setSearching(false);
//            intent.putExtra("cleanstr", cleanSize);
//            startActivity(intent);
//            finish();
//        }, 3000);
    }

    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 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(ScreenShotActivity.this, () -> {
                            finish();
                            return null;
                        },
                        () -> {
                            return null;
                        },
                        () -> {
                            finish();
                            return null;
                        });
            }
        });
        customScoreDialog.show();
    }

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