package com.key.vibekeyboard.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.key.vibekeyboard.data.database.AppDatabase;
import com.key.vibekeyboard.ui.adapter.WallpaperAdapter;
import com.key.vibekeyboard.ui.dialog.PermissionRequestDialog;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.data.database.entity.WallpaperInfo;
import com.key.vibekeyboard.utils.DownloadUtils;
import com.key.vibekeyboard.utils.InputMethodUtils;
import com.key.vibekeyboard.utils.ItemDecoration;
import com.key.vibekeyboard.databinding.ActivityDownloadBinding;
import com.key.vibekeyboard.topon.AdManager;
import com.key.vibekeyboard.topon.onActionListener;
import com.key.vibekeyboard.utils.TaskExecutorUtils;
import com.key.vibekeyboard.utils.unzipUtils;

import java.util.ArrayList;
import java.util.List;

public class DownloadActivity extends AppCompatActivity {

    private ActivityDownloadBinding binding;
    private String preview;
    private String url;
    private WallpaperInfo userdata;
    private Boolean dislike = false;
    private Boolean tempIsLike = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDownloadBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        AdManager.loadAllAd();

        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });

        initData();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (userdata != null && tempIsLike != null && tempIsLike != dislike) {
            userdata.setIslike(tempIsLike);
            TaskExecutorUtils.executeIO(() -> {
                AppDatabase.getInstance().wallpaperInfoDao().update(userdata);
            });
        }
        binding = null;
    }

    private void initData() {
        Intent intent = getIntent();
        WallpaperInfo wallpaperInfo = intent.getParcelableExtra("wallpaperInfo");
        ArrayList<WallpaperInfo> list = intent.getParcelableArrayListExtra("list");

        if (wallpaperInfo == null) {
            Toast.makeText(this, "Wallpapers info is missing!", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        preview = wallpaperInfo.getPreview();
        url = wallpaperInfo.getZipUrl();

        Log.d("DownloadActivity", "wallpaperInfo: " + wallpaperInfo);

        binding.downloadTitle.setText(wallpaperInfo.title);

        WallpaperAdapter adapter = new WallpaperAdapter(this, list);
        binding.downloadRecycler.setAdapter(adapter);
        binding.downloadRecycler.setLayoutManager(new GridLayoutManager(this, 2));
        binding.downloadRecycler.addItemDecoration(new ItemDecoration(16, 19, 10));

        TaskExecutorUtils.executeIO(() -> {
            List<WallpaperInfo> existingData = AppDatabase.getInstance().wallpaperInfoDao().checklikelist(preview);

            if (!existingData.isEmpty()) {
                userdata = existingData.get(0);
                dislike = userdata.getIslike();
                tempIsLike = dislike;

                runOnUiThread(() -> {
                    if (dislike) {
                        binding.downloadFavorite.setImageResource(android.R.drawable.btn_star_big_on);
                    } else {
                        binding.downloadFavorite.setImageResource(android.R.drawable.btn_star_big_off);
                    }
                });
            }
        });

        if (wallpaperInfo.getPreview() != null) {
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.splash)
                    .error(R.mipmap.splash)
                    .transform(new CenterCrop())
                    .transform(new RoundedCorners(16));

            Glide.with(this)
                    .load(wallpaperInfo.getPreview())
                    .apply(options)
                    .into(binding.downloadImage);
        } else {
            binding.downloadImage.setImageResource(R.mipmap.splash);
        }

    }


    private void initEvent() {

        binding.downloadBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdManager.showTopOn(DownloadActivity.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        finish();
                    }
                });
            }
        });

        binding.downloadDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdManager.showTopOn(DownloadActivity.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        downLoad();
                    }
                });
            }
        });

        binding.downloadFavorite.setOnClickListener(v -> checkLike());

        binding.downloadAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DownloadActivity.this, CategoryActivity.class);
                startActivity(intent);
            }
        });

    }

    private void downLoad() {
        ProgressBar progressBar = findViewById(R.id.progressBar);
        View view = findViewById(R.id.view);

        progressBar.setVisibility(View.VISIBLE);
        view.setVisibility(View.VISIBLE);

        if (!InputMethodUtils.isInputMethodEnabled() || !InputMethodUtils.isCurrentInputMethodActive()) {
            PermissionRequestDialog dialog = new PermissionRequestDialog();
            dialog.show(getSupportFragmentManager(), "PermissionRequestDialog");
            progressBar.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
        } else {
            DownloadUtils.downloadFile(this, url, (successful, resource) -> {
                if (successful) {
                    unzipUtils.unzipFile(this, resource, (successful1, resDirPath) -> {
                        if (successful1) {
                            SharedPreferences sharedPreferences = getSharedPreferences("keyboard_info", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("wallpaper_path", resDirPath);
                            editor.apply();

                            if (userdata != null) {
                                userdata.setPath(resDirPath);
                                userdata.setDownloaded(true);

                                TaskExecutorUtils.executeIO(() -> AppDatabase.getInstance().wallpaperInfoDao().update(userdata));
                            }
                        } else {
                            runOnUiThread(() -> {
                                Toast.makeText(DownloadActivity.this, "Decompression failure", Toast.LENGTH_SHORT).show();
                            });
                        }

                        runOnUiThread(() -> {
                            progressBar.setVisibility(View.GONE);
                            view.setVisibility(View.GONE);
                            Intent intent = new Intent(DownloadActivity.this, WriteActivity.class);
                            startActivity(intent);
                        });
                    });
                } else {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        view.setVisibility(View.GONE);
                    });
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {
                finish();
            }
        });
    }

    private void checkLike() {
        if (!tempIsLike) {
            binding.downloadFavorite.setImageResource(android.R.drawable.btn_star_big_on);
            tempIsLike = true;
        } else {
            binding.downloadFavorite.setImageResource(android.R.drawable.btn_star_big_off);
            tempIsLike = false;
        }
    }

}
