package com.wall.engine.wallpaper;

import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.ad.tradpluslibrary.TPAdManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.wall.engine.wallpaper.databinding.ActivityFullImageBinding;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;

// 壁纸设置类型常量
interface WallpaperType {
    int TYPE_HOME = 1;    // 桌面
    int TYPE_LOCK = 2;     // 锁屏
    int TYPE_BOTH = 3;     // 桌面+锁屏
}

public class FullImageActivity extends AppCompatActivity implements WallpaperType {
    // 传递参数Key
    public static final String EXTRA_IMAGE_URL = "extra_image_url";
    public static final String EXTRA_IMAGE_ID = "extra_image_id";
    public static final String EXTRA_IMAGE_DESC = "extra_image_desc";

    private ActivityFullImageBinding binding;
    private String imageUrl;
    private String imageId;
    private String imageDesc;
    private File tempFile; // 仅用于设置壁纸的临时文件
    private WallpaperManager wallpaperManager;
    private FavoriteManager favoriteManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFullImageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 沉浸式全屏
        initFullScreen();

        // 初始化管理器
        wallpaperManager = WallpaperManager.getInstance(this);
        favoriteManager = new FavoriteManager(this);

        // 获取传递的参数
        getIntentData();
        // 加载图片
        loadImage(imageUrl);
        // 初始化点击事件
        initClick();
        // 初始化点赞状态
        initFavoriteState();

        TPAdManager.INSTANCE.showTPAD(FullImageActivity.this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        });
    }

    private void initFullScreen() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        if (insetsController != null) {
            insetsController.hide(WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.navigationBars());
            insetsController.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
        }
    }

    private void getIntentData() {
        Intent intent = getIntent();
        imageUrl = intent.getStringExtra(EXTRA_IMAGE_URL);
        imageId = intent.getStringExtra(EXTRA_IMAGE_ID);
        imageDesc = intent.getStringExtra(EXTRA_IMAGE_DESC);

        if (imageDesc != null && !imageDesc.isEmpty()) {
            binding.tvContent.setText(imageDesc);
        } else {
            binding.tvContent.setText(getString(R.string.app_name));
        }

        // 初始化临时文件路径（应用私有目录，无需权限）
        if (imageId == null) {
            imageId = "wallpaper_" + System.currentTimeMillis();
        }
        tempFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), imageId + ".jpg");
    }

    private void loadImage(String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            Toast.makeText(this, "Image URL is empty, cannot load", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565)
                .placeholder(R.drawable.load_ing)
                .error(R.drawable.load_ing);

        // 检查临时文件是否存在
        if (tempFile.exists()) {
            Glide.with(this)
                    .load(tempFile)
                    .apply(options)
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .into(binding.imageviewPreview);
        } else {
            // 从网络加载
            Glide.with(this)
                    .asDrawable()
                    .load(imageUrl)
                    .apply(options)
                    .skipMemoryCache(true)
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.e("FullImage", "Failed to load image：" + e.getMessage());
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .centerCrop()
                    .into(binding.imageviewPreview);
        }
    }

    private void initFavoriteState() {
        if (imageId == null) return;
        boolean isFavorited = favoriteManager.isFavorite(imageId);
        binding.imageFavorite.setSelected(isFavorited);
        binding.imageFavorite.setImageResource(isFavorited ? R.drawable.like_red : R.drawable.like);
    }

    private void initClick() {
        // 返回按钮
        binding.imageviewBack.setOnClickListener(v -> finish());

        // 下载按钮（无需权限）
        binding.layoutDownload.setOnClickListener(v -> TPAdManager.INSTANCE.showTPAD(FullImageActivity.this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                startDownload();
                return null;
            }
        })
        );

        // 修正：设置壁纸按钮ID为button_set1（与布局一致）
        binding.buttonSet1.setOnClickListener(v -> TPAdManager.INSTANCE.showTPAD(FullImageActivity.this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                showWallpaperTypeDialog();
                return null;
            }
        }));

        // 点赞按钮
        binding.imageFavorite.setOnClickListener(v -> toggleFavorite());
    }

    private void toggleFavorite() {
        if (imageId == null) {
            Toast.makeText(this, "Cannot add to favorites", Toast.LENGTH_SHORT).show();
            return;
        }

        WallpaperItem item = new WallpaperItem();
        item.setId(imageId);
        item.setAlt_description(imageDesc);

        Urls urls = new Urls();
        urls.setRegular(imageUrl);
        urls.setSmall(imageUrl);
        urls.setFull(imageUrl);
        item.setUrls(urls);

        boolean isFavorited = favoriteManager.isFavorite(imageId);

        if (isFavorited) {
            favoriteManager.removeFavorite(imageId);
            binding.imageFavorite.setSelected(false);
            binding.imageFavorite.setImageResource(R.drawable.like);
            Toast.makeText(this, "Cancel collection", Toast.LENGTH_SHORT).show();
            Log.d("FullImageActivity", "Cancel collection: " + imageId);
        } else {
            favoriteManager.addFavorite(item);
            binding.imageFavorite.setSelected(true);
            binding.imageFavorite.setImageResource(R.drawable.like_red);
            Toast.makeText(this, "Favorited", Toast.LENGTH_SHORT).show();
            Log.d("FullImageActivity", "Favorited: " + imageId);
        }
    }

    /**
     * 核心：无需存储权限，直接通过MediaStore保存到相册
     */
    private void startDownload() {
        // 修正：加载进度条与下载按钮ID（与布局一致）
        showLoading(binding.pbDownload, binding.imageDownload, true);

        // 异步下载并写入相册
        new Thread(() -> {
            try {
                // 1. 下载图片到内存流
                URL url = new URL(imageUrl);
                URLConnection conn = url.openConnection();
                InputStream is = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                is.close();

                if (bitmap == null) {
                    throw new IOException("Failed to decode image");
                }

                // 2. 写入MediaStore（无需权限）
                ContentValues values = new ContentValues();
                // 设置图片信息
                values.put(MediaStore.Images.Media.DISPLAY_NAME, imageId + ".jpg");
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                // 相册显示路径：DCIM/Wallpaper
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/Wallpaper");
                values.put(MediaStore.Images.Media.WIDTH, bitmap.getWidth());
                values.put(MediaStore.Images.Media.HEIGHT, bitmap.getHeight());

                // Android 10+ 标记为待处理
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    values.put(MediaStore.Images.Media.IS_PENDING, 1);
                }

                // 插入到媒体库
                Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                if (imageUri == null) {
                    throw new IOException("Failed to import to media library");
                }

                // 写入图片数据
                try (OutputStream os = getContentResolver().openOutputStream(imageUri)) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                }

                // 完成插入（Android 10+）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    values.clear();
                    values.put(MediaStore.Images.Media.IS_PENDING, 0);
                    getContentResolver().update(imageUri, values, null, null);
                }

                // 保存临时文件（用于设置壁纸）
                saveTempFile(bitmap);

                // 主线程更新UI
                runOnUiThread(() -> {
                    showLoading(binding.pbDownload, binding.imageDownload, false);
                    Toast.makeText(this, "Download successful. Saved to your photo library", Toast.LENGTH_LONG).show();
                });

            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    showLoading(binding.pbDownload, binding.imageDownload, false);
                    Toast.makeText(FullImageActivity.this, "Download failed：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    /**
     * 保存临时文件到应用私有目录（用于设置壁纸，无需权限）
     */
    private void saveTempFile(Bitmap bitmap) throws IOException {
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        try (OutputStream os = new java.io.FileOutputStream(tempFile)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        }
    }


    private void showWallpaperTypeDialog() {
        // 1. 加载自定义弹窗布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_wallpaper_type, null);

        // 2. 获取布局中的三个选项容器
        LinearLayout layoutHome = dialogView.findViewById(R.id.layout_ic_home);
        LinearLayout layoutLock = dialogView.findViewById(R.id.layout_ic_lock);
        LinearLayout layoutBoth = dialogView.findViewById(R.id.layout_ic_both);

        // 3. 创建AlertDialog并设置透明背景（避免遮挡圆角）
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        // 4. 绑定选项点击事件
        layoutHome.setOnClickListener(v -> {
            setWallpaper(TYPE_HOME);
            dialog.dismiss();
        });

        layoutLock.setOnClickListener(v -> {
            setWallpaper(TYPE_LOCK);
            dialog.dismiss();
        });

        layoutBoth.setOnClickListener(v -> {
            setWallpaper(TYPE_BOTH);
            dialog.dismiss();
        });

        // 5. 显示弹窗并调整宽度
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(params);
        }
    }


    private void setWallpaper(int type) {
        // 修正：设置壁纸的进度条与按钮ID（与布局一致）
        showLoading(binding.pbSet1, binding.buttonSet1, true);

        // 修复Lambda变量问题：创建final变量
        final int finalType = type;

        if (!tempFile.exists()) {
            // 临时文件不存在，先下载
            new Thread(() -> {
                try {
                    URL url = new URL(imageUrl);
                    URLConnection conn = url.openConnection();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    is.close();

                    if (bitmap == null) {
                        throw new IOException("Failed to decode image");
                    }

                    // 保存临时文件
                    saveTempFile(bitmap);
                    // 设置壁纸
                    setWallpaperFromFile(tempFile, finalType);

                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        showLoading(binding.pbSet1, binding.buttonSet1, false);
                        Toast.makeText(FullImageActivity.this, "Setup failed", Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();
        } else {
            // 临时文件存在，直接设置
            new Thread(() -> setWallpaperFromFile(tempFile, finalType)).start();
        }
    }

    /**
     * 从临时文件设置壁纸
     */
    private void setWallpaperFromFile(File file, int type) {
        try {
            InputStream is = new java.io.FileInputStream(file);
            switch (type) {
                case TYPE_HOME:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(is, null, true, WallpaperManager.FLAG_SYSTEM);
                    } else {
                        wallpaperManager.setStream(is);
                    }
                    break;
                case TYPE_LOCK:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        wallpaperManager.setStream(is, null, true, WallpaperManager.FLAG_LOCK);
                    } else {
                        wallpaperManager.setStream(is);
                    }
                    break;
                case TYPE_BOTH:
                    wallpaperManager.setStream(is);
                    break;
            }
            is.close();

            runOnUiThread(() -> {
                showLoading(binding.pbSet1, binding.buttonSet1, false);
                Toast.makeText(this, "Wallpaper Updated", Toast.LENGTH_SHORT).show();
            });

        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(() -> {
                showLoading(binding.pbSet1, binding.buttonSet1, false);
                Toast.makeText(this, "Wallpaper setup failed：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            });
        }
    }

    private void showLoading(ProgressBar pb, View view, boolean show) {
        pb.setVisibility(show ? View.VISIBLE : View.GONE);
        view.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            initFullScreen();
        }
    }
}