package com.rainbow.app.keyboard.uiactivity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ad.tradpluslibrary.TPAdManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.rainbow.app.keyboard.App
import com.rainbow.app.keyboard.R
import com.rainbow.app.keyboard.javabean.DetailsjavaBean
import com.rainbow.app.keyboard.mycallback.KBClickCallback
import com.rainbow.app.keyboard.mycallback.EnablekbCallback
import com.rainbow.app.keyboard.mydb.DatabManager
import com.rainbow.app.keyboard.utils.UtilsCommon
import com.rainbow.app.keyboard.utils.UtilszipFile
import com.rainbow.app.keyboard.utils.UtilsSavecurrentkb
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.rainbow.app.keyboard.myadapter.KBItemAdapter
import kotlinx.coroutines.launch
import java.io.File

class DetailkbActivity : AppCompatActivity() {
    companion object {
        @JvmField
        var DISPLAY_URL_KEY: String = "display_url_key"
        @JvmField
        val ZIP_URL_KEY = "zip_url_key"
        @JvmField
        val NAME_KEY = "name_key"
        @JvmField
        val GIF_KEY = "gif_key"
        @JvmField
        val THUMB_KEY = "thumb_key"
        @JvmField
        val SOURCE_KEY = "data_key"
    }

    private var dialog: EnablekbDialog? = null
    private lateinit var displayUrl: String
    private lateinit var gifUrl: String
    private lateinit var zipUrl: String
    private lateinit var name: String
    private lateinit var applyBtn: LinearLayout
    private lateinit var imgData: ImageView
    private lateinit var imgBack: ImageView
    private lateinit var textName: TextView
    private lateinit var btnScrollToTop: ImageView
    private lateinit var recommendedRecycler: RecyclerView
    private lateinit var nestedScrollView: androidx.core.widget.NestedScrollView
    private lateinit var loadingLayout: FrameLayout
    private lateinit var unzipPath: String
    private lateinit var tvDownload: TextView
    private lateinit var imDownload: ImageView
    private lateinit var thumb: String
    private lateinit var imgLike: ImageView
    private lateinit var data: DetailsjavaBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detailkb)
        this.enableEdgeToEdge()
        TPAdManager.loadAllAd(this)
        showTPAD(this) { }
        ViewCompat.setOnApplyWindowInsetsListener(
            findViewById(R.id.main),
            OnApplyWindowInsetsListener { v: View, insets: WindowInsetsCompat ->
                val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
                v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
                insets
            })

        findViewId()
        getExtraData()
        displayData()
        setApply()
        onClick()
        setupScrollListener()  // 添加滚动监听
    }

    private fun findViewId() {
        applyBtn = findViewById(R.id.layoutDownloadApply)
        imgData = findViewById(R.id.image_data)
        imgBack = findViewById(R.id.back)
        textName = findViewById(R.id.textview_data_name)
        recommendedRecycler = findViewById(R.id.recommended_recycler)
        nestedScrollView = findViewById(R.id.nested_scroll_view)  // NestedScrollView
        btnScrollToTop = findViewById(R.id.btn_scroll_to_top)
        imgLike = findViewById(R.id.im_like)
        loadingLayout = findViewById(R.id.loading)
        imDownload = findViewById(R.id.im_download)
        tvDownload = findViewById(R.id.tv_download)
    }

    private fun getExtraData() {
        data = intent.getSerializableExtra(SOURCE_KEY) as DetailsjavaBean
        displayUrl = intent.getStringExtra(DISPLAY_URL_KEY).toString()
        zipUrl = intent.getStringExtra(ZIP_URL_KEY).toString()
        name = intent.getStringExtra(NAME_KEY).toString()
        gifUrl = intent.getStringExtra(GIF_KEY).toString()
        thumb = intent.getStringExtra(THUMB_KEY).toString()

        val serviceZipName = UtilszipFile.getServiceZipName(zipUrl)
        unzipPath = UtilszipFile.getUnzipPath(serviceZipName)

        Log.d("KeyboardActivity", "unzipPath=$unzipPath")

        lifecycleScope.launch {
            DatabManager.getIsLike(name) {
                imgLike.isSelected = it
            }
        }

        if (File(unzipPath).exists()) {
            imDownload.isVisible = false
            tvDownload.text = getString(R.string.apply)
        } else {
            imDownload.isVisible = true
            tvDownload.text = getString(R.string.download_apply)
        }
    }

    private fun displayData() {
        textName.text = name
        textName.setTypeface(textName.typeface, Typeface.BOLD)

        if (gifUrl.isNotEmpty()) {
            loadImgGif()
        } else {
            Glide.with(this)
                .load(displayUrl)
                .thumbnail(Glide.with(this).load(thumb))
                .into(imgData)
        }
    }

    private fun onClick() {
        imgBack.setOnClickListener {
            finish()
        }

        imgLike.setOnClickListener {
            showTPAD(this) {
                imgLike.isSelected = !imgLike.isSelected
                lifecycleScope.launch {
                    if (imgLike.isSelected) {
                        DatabManager.addLike(data)
                    } else {
                        DatabManager.removeLike(data)
                    }
                }
            }

        }

        // 回到顶部按钮点击事件
        btnScrollToTop.setOnClickListener {
            nestedScrollView.smoothScrollTo(0, 0)
            btnScrollToTop.visibility = View.GONE
        }

        val forYouList = App.Companion.list.filter {
            it.parentName == getString(R.string.recommend_name)
        }

        recommendedRecycler.run {
            adapter = KBItemAdapter(this@DetailkbActivity).apply {
                val shuffled = forYouList[0].keyboardList.shuffled()
                setData(shuffled)
                applyRecoItemConfig() // 应用RecoItem配置
                setItemClickListener(object : KBClickCallback {
                    override fun OnItemClickListener() {
                        finish()
                    }
                })
            }
            layoutManager = GridLayoutManager(this@DetailkbActivity, 2) // 保持2列网格
        }
    }

    // ==================== 滚动监听器 ====================
    private fun setupScrollListener() {
        nestedScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            // 当滚动超过200像素时显示回到顶部按钮
            if (scrollY > 200) {
                btnScrollToTop.visibility = View.VISIBLE
            } else {
                btnScrollToTop.visibility = View.GONE
            }
        }

        // 也可以为RecyclerView添加监听（双重保险）
        recommendedRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 获取NestedScrollView的滚动位置
                val scrollY = nestedScrollView.scrollY
                if (scrollY > 200) {
                    btnScrollToTop.visibility = View.VISIBLE
                } else {
                    btnScrollToTop.visibility = View.GONE
                }
            }
        })

        // 初始检查一次
        nestedScrollView.post {
            val scrollY = nestedScrollView.scrollY
            btnScrollToTop.visibility = if (scrollY > 200) View.VISIBLE else View.GONE
        }
    }

    @SuppressLint("CheckResult")
    private fun loadImgGif() {
        Glide.with(this)
            .load(gifUrl)
            .thumbnail(Glide.with(this).load(thumb))
            .addListener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable>?,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    if (resource is WebpDrawable) {
                        resource.loopCount = WebpDrawable.LOOP_FOREVER
                    }
                    return false
                }
            }).into(imgData)
    }

    private fun setApply() {
        applyBtn.setOnClickListener {
            val checkEnable = UtilsCommon.checkEnable(this)
            val checkSetDefault = UtilsCommon.checkSetDefault(this)
            if (!checkEnable || !checkSetDefault) {
                showDialog()
                return@setOnClickListener
            }
            startDown()
        }
    }

    private fun showDialog() {
        dialog = dialog ?: EnablekbDialog.newInstance()
        dialog?.setClickListener {
            startDown()
        }
        dialog?.show(supportFragmentManager, "")
    }

    private fun startDown() {
        showTPAD(this) {
            loadingLayout.isVisible = true
            applyBtn.isEnabled = false

            val file = File(unzipPath)
            if (file.exists()) {
                val findFirstDirectory = UtilszipFile.findFirstDirectory(file)
                apply("${findFirstDirectory}/")
                applyBtn.isEnabled = true
                loadingLayout.isVisible = false
            } else {
                UtilszipFile.startDownloadZip(zipUrl, object : EnablekbCallback {
                    override fun OnApplySkinListener(fileList: List<File?>?) {
                        runOnUiThread {
                            applyBtn.isEnabled = true
                            loadingLayout.isVisible = false
                        }
                        if (fileList.isNullOrEmpty()) {
                            runOnUiThread {
                                Toast.makeText(
                                    this@DetailkbActivity,
                                    getString(R.string.download_fail),
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        } else {
                            if (file.exists()) {
                                val findFirstDirectory = UtilszipFile.findFirstDirectory(file)
                                Log.d(
                                    App.Companion.TAG,
                                    "----apply------------it=$findFirstDirectory"
                                )
                                runOnUiThread {
                                    apply("${findFirstDirectory}/")
                                }
                            }
                        }
                    }
                })
            }
        }

    }

    private fun apply(path: String) {
        var skinParentPath = path
        if (path.contains("res")) {
            skinParentPath = path.substringBeforeLast("res")
        }

        UtilsSavecurrentkb.updateSkinPath(skinParentPath)
        Toast.makeText(
            this@DetailkbActivity,
            getString(R.string.theme_application_successful),
            Toast.LENGTH_SHORT
        ).show()
        startActivity(Intent(this, EditVActivity::class.java).apply {
            putExtra(EditVActivity.key_name, name)
        })
        finish()
    }
}