package com.key.vibekeyboard.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.appcompat.app.AppCompatActivity;
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.Adapter.DownlaodRecyclerViewAdapter;
import com.key.vibekeyboard.Dialog.PermissionRequestDialog;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.Room.MyDatabase;
import com.key.vibekeyboard.Room.WallpaperInfo;
import com.key.vibekeyboard.Utils.ItemDecoration;
import com.key.vibekeyboard.Utils.Mytool;
import com.key.vibekeyboard.Utils.StaticValue;
import com.key.vibekeyboard.databinding.ActivityDownloadBinding;

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

public class DownloadActivity extends AppCompatActivity {

    private ActivityDownloadBinding binding;
    private String preview;
    private String url;
    private String unzipPath;
    private WallpaperInfo otherdata;
    private Boolean islike = false;
    private Boolean tempIsLike = false; // 用来暂存状态


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

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

        initData();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (otherdata != null && tempIsLike != null && tempIsLike != islike) {
            otherdata.setIslike(tempIsLike);
            Mytool.runIO(() -> {
                MyDatabase.getInstance().wallpaperInfoDao().update(otherdata);
            });
        }
        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();
        String name = wallpaperInfo.getTitle();
        url = wallpaperInfo.getZipUrl();

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

        binding.downloadTitle.setText(wallpaperInfo.title);

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

        Mytool.runIO(() -> {
            List<WallpaperInfo> existingData = MyDatabase.getInstance().wallpaperInfoDao().checklikelist(preview);

            if (!existingData.isEmpty()) {
                otherdata = existingData.get(0);
                islike = otherdata.getIslike();
                tempIsLike = islike; // Store the initial islike value

                String path = StaticValue.PATH;

                if (path.equals(otherdata.getPath())) {
                    runOnUiThread(() -> {
                        // Update UI if needed
                    });
                }

                runOnUiThread(() -> {
                    // Update the favorite icon based on the islike value
                    if (islike) {
                        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);
        }

        unzipPath = getCacheDir() + "/" + name;
    }


    private void initEvent() {

        binding.downloadBack.setOnClickListener(v -> finish());

        binding.downloadDownload.setOnClickListener(v -> 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 (!Mytool.isStep1() || !Mytool.isStep2()) {
            PermissionRequestDialog dialog = new PermissionRequestDialog();
            dialog.show(getSupportFragmentManager(), "PermissionRequestDialog");
            // 操作结束后隐藏进度条
            progressBar.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
        } else {
            Mytool.donwnZip(this, url, (successful, resource) -> {
                if (successful) {
                    Mytool.unZip(this, unzipPath, resource, (successful1, resDirPath) -> {
                        if (successful1) {
                            // 将路径存储到 SharedPreferences
                            SharedPreferences sharedPreferences = getSharedPreferences("keyboard_prefs", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("wallpaper_path", resDirPath);
                            editor.apply();  // 使用 apply() 异步保存

                            StaticValue.PATH = resDirPath;

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

                                Mytool.runIO(() -> MyDatabase.getInstance().wallpaperInfoDao().update(otherdata));
                            }
                        } 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);
                    });
                }
            });
        }
    }

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

}
