package com.wallpaper.wallpaperbox.ui.activity;

import static com.wallpaper.wallpaperbox.util.WallpaperUtils.REQUEST_CODE_WRITE_EXTERNAL_STORAGE;

import android.app.WallpaperManager;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.wallpaper.wallpaperbox.R;
import com.wallpaper.wallpaperbox.data.entity.WallpaperEntity;
import com.wallpaper.wallpaperbox.databinding.ActivityDetailBinding;
import com.wallpaper.wallpaperbox.topon.AdManager;
import com.wallpaper.wallpaperbox.topon.onActionListener;
import com.wallpaper.wallpaperbox.ui.viewmodel.WallpaperViewModel;
import com.wallpaper.wallpaperbox.util.WallpaperUtils;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DetailActivity extends AppCompatActivity {
    private ActivityDetailBinding binding;
    private String imagePathOriginal;
    private String imagePathSource;
    private WallpaperEntity wallpaperEntity;
    private String name;
    private Bitmap bitmap;
    private WallpaperUtils wallpaperUtils;
    private WallpaperViewModel wallpaperViewModel;
    private ExecutorService executorService;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            int navigationBars = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
            v.setPadding(0, 0, 0, navigationBars);
            return insets;
        });

        initializeData();
        initializeEvents();
    }

    private void initializeData() {
        AdManager.loadAllAd();

        wallpaperEntity = (WallpaperEntity) getIntent().getSerializableExtra("wallpaper");
        if (wallpaperEntity != null) {
            imagePathOriginal = wallpaperEntity.getOriginal();
            imagePathSource = wallpaperEntity.getSource();
            name = wallpaperEntity.getName();
        } else {
            finish();
        }

        handler = new Handler(Looper.getMainLooper());
        executorService = Executors.newSingleThreadExecutor();

        wallpaperViewModel = new ViewModelProvider(this).get(WallpaperViewModel.class);

        wallpaperUtils = new WallpaperUtils(binding.progressBar, binding.view);
    }

    private void initializeEvents() {
        showProgress();

        binding.back.setOnClickListener(v -> {
            AdManager.showTopOn(DetailActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });
        });

        binding.like.setOnClickListener(v -> {
            boolean newStatus = !wallpaperEntity.getLike();
            wallpaperEntity.setLike(newStatus);
            wallpaperViewModel.update(wallpaperEntity);
        });

        binding.set.setOnClickListener(v -> {
            AdManager.showTopOn(DetailActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    showCustomBottomSheetDialog();
                }
            });
        });

        binding.downPicture.setOnClickListener(v -> {
            AdManager.showTopOn(DetailActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    showProgress();
                    wallpaperUtils.saveToGallery(DetailActivity.this, imagePathSource);
                }
            });
        });

        loadImage();
        loadFavorite();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                wallpaperUtils.saveToGallery(this, imagePathSource);
            } else {
                Toast.makeText(this, "Write permission to external storage is denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showCustomBottomSheetDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.set_wallpaper_dialog, null);

        dialogView.findViewById(R.id.both).setOnClickListener(v -> {
            handleWallpaperAction(bitmap, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK);
            bottomSheetDialog.dismiss();
        });

        dialogView.findViewById(R.id.lock).setOnClickListener(v -> {
            handleWallpaperAction(bitmap, WallpaperManager.FLAG_LOCK);
            bottomSheetDialog.dismiss();
        });

        dialogView.findViewById(R.id.desktop).setOnClickListener(v -> {
            handleWallpaperAction(bitmap, WallpaperManager.FLAG_SYSTEM);
            bottomSheetDialog.dismiss();
        });

        bottomSheetDialog.setContentView(dialogView);
        bottomSheetDialog.show();
    }

    private void handleWallpaperAction(Bitmap bitmap, int flag) {
        showProgress();
        executorService.submit(() -> {
            try {
                setWallpaper(bitmap, flag);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                handler.post(() -> {
                    hideProgress();
                    binding.set.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "Wallpaper setting is successful", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void setWallpaper(Bitmap bitmap, int flag) {
        executorService.submit(() -> {
            WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
            try {
                binding.imageView.setDrawingCacheEnabled(true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    wm.setBitmap(bitmap, null, true, flag);
                } else {
                    wm.setBitmap(bitmap);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void loadImage() {
        Glide.with(this)
                .asBitmap()
                .load(imagePathOriginal)
                .error(ContextCompat.getDrawable(this, R.mipmap.placeholder))
                .override(1080, 1920)
                .centerInside()
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        binding.imageView.setImageBitmap(resource);
                        bitmap = resource;
                        hideProgress();
                    }

                    @Override
                    public void onLoadCleared(Drawable placeholder) {
                        binding.imageView.setImageDrawable(placeholder != null ? placeholder : getDefaultPlaceholder());
                    }

                    @Override
                    public void onLoadFailed(Drawable errorDrawable) {
                        binding.imageView.setImageDrawable(errorDrawable != null ? errorDrawable : getDefaultPlaceholder());
                        hideProgress();
                    }
                });
    }

    private Drawable getDefaultPlaceholder() {
        return ContextCompat.getDrawable(this, R.mipmap.placeholder);
    }

    private void loadFavorite() {
        wallpaperViewModel.getWallpaperLike(imagePathSource, name).observe(this, wallpaper -> setFavoriteButton());
    }

    private void setFavoriteButton() {
        binding.like.setImageResource(
                wallpaperEntity.getLike() ? R.drawable.like : R.drawable.un_like
        );
    }

    private void hideProgress() {
        binding.progressBar.setVisibility(View.GONE);
        binding.view.setVisibility(View.GONE);
    }

    private void showProgress() {
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.view.setVisibility(View.VISIBLE);
    }

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