package com.gallery.free.wallpaper

import androidx.activity.OnBackPressedCallback
import android.app.WallpaperManager
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ad.ironsourcelibrary.ActionListener
import com.ad.ironsourcelibrary.ISAdManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gallery.free.wallpaper.databinding.ActivityLocalpreBinding
import java.lang.ref.WeakReference

class LocalPreActivity : AppCompatActivity(),
    Dialog_SetWp.OnWallpaperTypeSelectedListener {

    private lateinit var binding: ActivityLocalpreBinding
    private lateinit var wallpaperManager: WallpaperManager
    private var setWallpaperDialog: Dialog_SetWp? = null
    private var isSettingWallpaper = false
    private var currentWallpaperBitmap: Bitmap? = null
    private var imageUri: Uri? = null
    private var screenWidth = 0
    private var screenHeight = 0
    private var isLaunchedFromSetting = false
    private var hasShownSuccessToast = false
    private var isInGallerySelection = false

    companion object {
        private const val TAG = "LocalImagePreview"
        private const val SET_WALLPAPER_STATE_IDLE = 0
        private const val SET_WALLPAPER_STATE_LOADING = 1
        private const val SET_WALLPAPER_STATE_SUCCESS = 2
        private const val SET_WALLPAPER_STATE_FAILED = 3
        private const val DELAY_BEFORE_RETURN = 800L
        private const val REQUEST_GALLERY_AGAIN = 1001

        const val EXTRA_IMAGE_URI = "selected_image_uri"
        const val EXTRA_FROM_SETTING = "from_setting"
        const val RESULT_SET_SUCCESS = 200
    }

    private var setWallpaperState = SET_WALLPAPER_STATE_IDLE
    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Utils_com.initFull(this, true)
        ISAdManager.loadAllAd()
        setTheme(R.style.TransparentPreviewTheme)

        overridePendingTransition(0, 0)

        binding = ActivityLocalpreBinding.inflate(layoutInflater)
        setContentView(binding.root)

        overridePendingTransition(0, 0)

        binding = ActivityLocalpreBinding.inflate(layoutInflater)
        setContentView(binding.root)

        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                handleBackButtonClick()
            }
        })
        ISAdManager.showIsAd(this@LocalPreActivity,object : ActionListener{
            override fun onAction() {

            }

        })
        Log.d(TAG, "=== LocalImagePreviewActivity_onCreate ===")
        Log.d(TAG, "Activity实例: ${this.hashCode()}")

        showLoading(true)

        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        screenWidth = displayMetrics.widthPixels
        screenHeight = displayMetrics.heightPixels
        Log.d(TAG, "Screen size: $screenWidth x $screenHeight")

        wallpaperManager = WallpaperManager.getInstance(this)

        // 获取图片URI
        val intentUri = intent.getStringExtra(EXTRA_IMAGE_URI)?.let { Uri.parse(it) }
        if (intentUri != null) {
            imageUri = intentUri
            Log.d(TAG, "从Intent获取图片URI: $imageUri")
        }

        isLaunchedFromSetting = intent.getBooleanExtra(EXTRA_FROM_SETTING, true)
        Log.d(TAG, "是否从设置页面启动: $isLaunchedFromSetting")

        if (imageUri == null) {
            Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show()
            showLoading(false)
            finish()
            return
        }

        // 检查是否是重新创建的情况
        if (savedInstanceState != null) {
            Log.d(TAG, "Activity被重新创建")
            setWallpaperState = savedInstanceState.getInt("setWallpaperState", SET_WALLPAPER_STATE_IDLE)
            isLaunchedFromSetting = savedInstanceState.getBoolean("isLaunchedFromSetting", true)
            isInGallerySelection = savedInstanceState.getBoolean("isInGallerySelection", false)
            updateSetWallpaperButtonState()
        }

        hideSystemUI()
        setupViews()
        loadImage()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("setWallpaperState", setWallpaperState)
        outState.putBoolean("isLaunchedFromSetting", isLaunchedFromSetting)
        outState.putBoolean("isInGallerySelection", isInGallerySelection)
        Log.d(TAG, "保存状态: setWallpaperState=$setWallpaperState, isLaunchedFromSetting=$isLaunchedFromSetting, isInGallerySelection=$isInGallerySelection")
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        Log.d(TAG, "onNewIntent被调用")

        // 当Activity已经存在时，更新URI
        val newUri = intent?.getStringExtra(EXTRA_IMAGE_URI)?.let { Uri.parse(it) }
        if (newUri != null && newUri != imageUri) {
            imageUri = newUri
            currentWallpaperBitmap = null
            setWallpaperState = SET_WALLPAPER_STATE_IDLE

            // 检查是否从设置页面启动
            isLaunchedFromSetting = intent.getBooleanExtra(EXTRA_FROM_SETTING, false)

            Log.d(TAG, "更新图片URI: $imageUri, 是否从设置页面启动: $isLaunchedFromSetting")
            loadImage()
            updateSetWallpaperButtonState()
        }
    }

    private fun hideSystemUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.let { controller ->
                controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
                controller.systemBarsBehavior =
                    WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        }
    }

    private fun setupViews() {
        Log.d(TAG, "setupViews")

        // 返回按钮
        binding.buttonBack.setOnClickListener {
            Log.d(TAG, "Back button clicked")
            handleBackButtonClick()
        }

        // 设置壁纸按钮
        binding.buttonSetWallpaper.setOnClickListener {
            Log.d(TAG, "Set wallpaper button clicked")
            if (setWallpaperState != SET_WALLPAPER_STATE_LOADING) {
                showSetWallpaperDialog()
            }
        }

        updateSetWallpaperButtonState()
    }

    private fun updateSetWallpaperButtonState() {
        Log.d(TAG, "更新按钮状态: $setWallpaperState")

        when (setWallpaperState) {
            SET_WALLPAPER_STATE_IDLE -> {
                binding.buttonSetWallpaper.setImageResource(R.drawable.ic_setwp)
                binding.buttonSetWallpaper.isEnabled = true
                binding.buttonBack.isEnabled = true
            }

            SET_WALLPAPER_STATE_LOADING -> {
                binding.buttonSetWallpaper.setImageResource(R.drawable.loading_animation)
                binding.buttonSetWallpaper.isEnabled = false
                binding.buttonBack.isEnabled = false
            }

            SET_WALLPAPER_STATE_SUCCESS -> {
                binding.buttonSetWallpaper.setImageResource(R.drawable.ic_success)
                binding.buttonSetWallpaper.isEnabled = false
                binding.buttonBack.isEnabled = false

                if (!hasShownSuccessToast) {
                    Toast.makeText(this, "setting successfully!", Toast.LENGTH_SHORT).show()
                    hasShownSuccessToast = true
                }

                setResult(RESULT_SET_SUCCESS)

                handler.postDelayed({
                    returnToSettingFragment()
                }, DELAY_BEFORE_RETURN)
            }

            SET_WALLPAPER_STATE_FAILED -> {
                binding.buttonSetWallpaper.setImageResource(R.drawable.close_detailwp)
                binding.buttonSetWallpaper.isEnabled = true
                binding.buttonBack.isEnabled = true

                // 设置失败：显示Toast
                Toast.makeText(this, "setting failed...", Toast.LENGTH_SHORT).show()

                handler.postDelayed({
                    setWallpaperState = SET_WALLPAPER_STATE_IDLE
                    updateSetWallpaperButtonState()
                }, DELAY_BEFORE_RETURN)
            }
        }
    }
    private fun returnToSettingFragment() {
        try {
            Log.d(TAG, "返回到SettingFragment，isLaunchedFromSetting=$isLaunchedFromSetting")

            if (isLaunchedFromSetting) {
                val settingIntent = Intent(this, MainActivity::class.java).apply {
                    putExtra("SHOW_SETTING_FRAGMENT", true)

                    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                }

                startActivity(settingIntent)
                finish()
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                Log.d(TAG, "已启动MainActivity显示SettingFragment")
            } else {
                Log.d(TAG, "不是从设置页面启动，直接结束")
                finish()
            }
        } catch (e: Exception) {
            Log.e(TAG, "返回SettingFragment失败: ${e.message}")
            finish()  // 如果失败，至少正常结束
        }
    }
    private var isFinishingByUser = false
    private var isProcessingBack = false

    private fun handleBackButtonClick() {
        // 如果正在设置中，禁止返回
        if (setWallpaperState == SET_WALLPAPER_STATE_LOADING ||
            setWallpaperState == SET_WALLPAPER_STATE_SUCCESS
        ) {
            return
        }

        // 防止重复点击
        if (isProcessingBack) return
        isProcessingBack = true

        // 标记为用户主动关闭
        isFinishingByUser = true

        Toast.makeText(this, "setting cancelled...", Toast.LENGTH_SHORT).show()

        currentWallpaperBitmap = null

        handler.postDelayed({
            try {
                if (isInGallerySelection) {
                    // 如果用户正在重新选择图片（已经在图库中），返回到设置页面
                    Log.d(TAG, "用户在图库中点击返回，返回到设置页面")
                    returnToSettingFragment()
                } else {
                    // 用户在预览页面点击返回，重新打开图库
                    Log.d(TAG, "用户在预览页面点击返回，重新打开图库")
                    isInGallerySelection = true  // 标记为正在重新选择
                    openGalleryForNewImage()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                returnToSettingFragment()  // 如果出错，也返回到设置页面
            } finally {
                isProcessingBack = false
                isFinishingByUser = false
            }
        }, 300)
    }

    private fun openGalleryForNewImage() {
        try {
            val galleryIntent = Intent(Intent.ACTION_PICK)
            galleryIntent.type = "image/*"

            galleryIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)

            startActivityForResult(galleryIntent, REQUEST_GALLERY_AGAIN)
            Log.d(TAG, "打开图库选择新图片")
        } catch (e: Exception) {
            Log.e(TAG, "打开图库失败: ${e.message}")
            Toast.makeText(this, "无法打开图库", Toast.LENGTH_SHORT).show()
            returnToSettingFragment()  // 失败时返回到设置页面
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d(TAG, "onActivityResult: requestCode=$requestCode, resultCode=$resultCode, isLaunchedFromSetting=$isLaunchedFromSetting, isInGallerySelection=$isInGallerySelection")

        when (requestCode) {
            REQUEST_GALLERY_AGAIN -> {
                // 重置状态
                isInGallerySelection = false

                if (resultCode == android.app.Activity.RESULT_OK && data != null) {
                    val uri = data.data
                    if (uri != null) {
                        // 用户重新选择了图片
                        Log.d(TAG, "用户重新选择了图片: $uri")

                        // 启动新的预览页面
                        val newIntent = Intent(this, LocalPreActivity::class.java).apply {
                            putExtra(EXTRA_IMAGE_URI, uri.toString())
                            putExtra(EXTRA_FROM_SETTING, isLaunchedFromSetting)
                        }

                        // 结束当前预览页面
                        finish()

                        // 延迟启动新预览页面
                        handler.postDelayed({
                            startActivity(newIntent)
                            overridePendingTransition(0, 0)
                        }, 100)
                    } else {
                        // 没有获取到图片，返回到设置页面
                        Log.d(TAG, "图库返回但没有选择图片，返回到设置页面")
                        returnToSettingFragment()
                    }
                } else {
                    // 用户取消了图库选择，返回到设置页面
                    Log.d(TAG, "用户取消了图库选择，返回到设置页面")
                    returnToSettingFragment()
                }
            }
        }
    }

    private fun loadImage() {
        Log.d(TAG, "开始加载图片: $imageUri")

        // 先显示加载状态
        showLoading(true)

        // 重置状态
        setWallpaperState = SET_WALLPAPER_STATE_IDLE
        updateSetWallpaperButtonState()

        // 加载预览图
        Glide.with(this)
            .load(imageUri)
            .into(binding.imageViewPreview)

        // 加载Bitmap供设置壁纸使用
        Glide.with(this)
            .asBitmap()
            .load(imageUri)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    currentWallpaperBitmap = resource
                    showLoading(false)
                    Log.d(TAG, "图片加载成功，大小: ${resource.width}x${resource.height}")
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    showLoading(false)
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    showLoading(false)
                    Toast.makeText(
                        this@LocalPreActivity,
                        "Failed to load image",
                        Toast.LENGTH_SHORT
                    ).show()
                    Log.e(TAG, "图片加载失败: $imageUri")

                    // 根据启动源返回不同的结果
                    if (isLaunchedFromSetting) {
                        setResult(android.app.Activity.RESULT_CANCELED)
                    }
                    finish()
                }
            })
    }

    private fun showLoading(show: Boolean) {
        binding.progressBar.visibility = if (show) View.VISIBLE else View.GONE
    }

    private fun showSetWallpaperDialog() {
        if (setWallpaperDialog == null) {
            setWallpaperDialog = Dialog_SetWp()
            setWallpaperDialog?.setListener(this)
        }
        if (setWallpaperDialog?.isAdded != true) {
            setWallpaperDialog?.show(supportFragmentManager, "SetWallpaperDialog")
        }
    }

    override fun onWallpaperTypeSelected(type: Int) {
        setWallpaper(type)
    }

    private fun setWallpaper(type: Int) {
        if (isSettingWallpaper || setWallpaperState == SET_WALLPAPER_STATE_SUCCESS) return

        Log.d(TAG, "开始设置壁纸，类型: $type, 是否从设置页面启动: $isLaunchedFromSetting")

        isSettingWallpaper = true
        setWallpaperState = SET_WALLPAPER_STATE_LOADING
        updateSetWallpaperButtonState()

        if (currentWallpaperBitmap != null) {
            SetWallpaperTask(this, type, currentWallpaperBitmap!!).execute()
            return
        }

        // 如果Bitmap还没缓存，重新加载
        Glide.with(this)
            .asBitmap()
            .load(imageUri)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    currentWallpaperBitmap = resource
                    SetWallpaperTask(this@LocalPreActivity, type, resource).execute()
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // 清理资源
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    isSettingWallpaper = false
                    setWallpaperState = SET_WALLPAPER_STATE_FAILED
                    updateSetWallpaperButtonState()
                }
            })
    }

    private class SetWallpaperTask(
        activity: LocalPreActivity,
        private val type: Int,
        private val bitmap: Bitmap
    ) : AsyncTask<Void, Void, Boolean>() {

        private val activityRef = WeakReference(activity)

        private fun createCenteredWallpaperBitmap(
            originalBitmap: Bitmap,
            screenWidth: Int,
            screenHeight: Int
        ): Bitmap {
            val bitmapWidth = originalBitmap.width.toFloat()
            val bitmapHeight = originalBitmap.height.toFloat()

            // 计算缩放比例，使图片至少能覆盖整个屏幕
            val scaleX = screenWidth / bitmapWidth
            val scaleY = screenHeight / bitmapHeight
            val scale = maxOf(scaleX, scaleY)

            // 创建缩放后的图片
            val matrix = Matrix()
            matrix.postScale(scale, scale)
            val scaledBitmap = Bitmap.createBitmap(
                originalBitmap,
                0, 0,
                originalBitmap.width, originalBitmap.height,
                matrix, true
            )

            // 从缩放后的图片中裁剪出居中区域
            val scaledWidth = scaledBitmap.width
            val scaledHeight = scaledBitmap.height

            // 计算裁剪的起始点（居中）
            val startX = (scaledWidth - screenWidth) / 2
            val startY = (scaledHeight - screenHeight) / 2

            // 确保裁剪区域在图片范围内
            val safeStartX = maxOf(0, startX)
            val safeStartY = maxOf(0, startY)
            val safeEndX = minOf(safeStartX + screenWidth, scaledWidth)
            val safeEndY = minOf(safeStartY + screenHeight, scaledHeight)
            val safeWidth = safeEndX - safeStartX
            val safeHeight = safeEndY - safeStartY

            // 创建最终居中裁剪的图片
            return Bitmap.createBitmap(
                scaledBitmap,
                safeStartX, safeStartY,
                safeWidth, safeHeight
            )
        }

        override fun doInBackground(vararg params: Void?): Boolean {
            val activity = activityRef.get() ?: return false

            return try {
                Log.d("SetWallpaperTask", "开始处理壁纸图片")

                // 创建居中裁剪的壁纸
                val centeredBitmap = createCenteredWallpaperBitmap(
                    bitmap,  // 注意：这里的bitmap是Glide管理的，不要回收它
                    activity.screenWidth,
                    activity.screenHeight
                )

                Log.d("SetWallpaperTask", "裁剪后图片大小: ${centeredBitmap.width}x${centeredBitmap.height}")

                // 根据选择的类型设置壁纸
                when (type) {
                    Dialog_SetWp.TYPE_HOME -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            activity.wallpaperManager.setBitmap(
                                centeredBitmap,
                                null,
                                true,
                                WallpaperManager.FLAG_SYSTEM
                            )
                        } else {
                            activity.wallpaperManager.setBitmap(centeredBitmap)
                        }
                        Log.d("SetWallpaperTask", "设置主屏幕壁纸")
                    }

                    Dialog_SetWp.TYPE_LOCK -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            activity.wallpaperManager.setBitmap(
                                centeredBitmap,
                                null,
                                true,
                                WallpaperManager.FLAG_LOCK
                            )
                        } else {
                            activity.wallpaperManager.setBitmap(centeredBitmap)
                        }
                        Log.d("SetWallpaperTask", "设置锁屏壁纸")
                    }

                    Dialog_SetWp.TYPE_BOTH -> {
                        activity.wallpaperManager.setBitmap(centeredBitmap)
                        Log.d("SetWallpaperTask", "设置主屏幕和锁屏壁纸")
                    }
                }

                // 关键修复点2：只回收自己创建的centeredBitmap
                // 不回收传入的bitmap（因为它是Glide管理的）
                centeredBitmap.recycle()

                true
            } catch (e: Exception) {
                Log.e("SetWallpaperTask", "设置壁纸失败: ${e.message}", e)
                false
            }
        }

        override fun onPostExecute(success: Boolean) {
            val activity = activityRef.get() ?: return

            activity.isSettingWallpaper = false

            if (success) {
                // 设置成功
                activity.setWallpaperState = SET_WALLPAPER_STATE_SUCCESS
                Log.d("SetWallpaperTask", "壁纸设置成功，启动源: ${activity.isLaunchedFromSetting}")
            } else {
                // 设置失败
                activity.setWallpaperState = SET_WALLPAPER_STATE_FAILED
                Log.d("SetWallpaperTask", "壁纸设置失败")
            }

            activity.updateSetWallpaperButtonState()
        }
    }
    override fun finish() {
        super.finish()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "Activity销毁: ${this.hashCode()}, 是否从设置页面启动: $isLaunchedFromSetting")

        isSettingWallpaper = false
        if (!isDestroyed && !isFinishing) {
            Glide.with(this).clear(binding.imageViewPreview)
        } else {
            Log.w(TAG, "Activity已销毁或正在结束，跳过Glide清理")
        }
        currentWallpaperBitmap = null

        handler.removeCallbacksAndMessages(null)
    }
}