package com.app.intelligent.board.uiactivity

import android.annotation.SuppressLint
import android.content.Intent
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.ProgressBar
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.viewpager2.widget.ViewPager2
import com.ad.tradpluslibrary.TPAdManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.app.intelligent.board.AppContextHelper
import com.app.intelligent.board.R
import com.app.intelligent.board.uimodel.KeyboardItemInfo
import com.app.intelligent.board.uilistener.KeyboardItemClickListener
import com.app.intelligent.board.uilistener.KeyboardConfigChangeListener
import com.app.intelligent.board.uidb.MyAppDatabaseManager
import com.app.intelligent.board.uiadapter.KeyboardItemAdapter
import com.app.intelligent.board.uifragment.KeyboardActivationDialog
import com.app.intelligent.board.utils.AppCommonUtils
import com.app.intelligent.board.utils.KeyboardZipFileHandler
import com.app.intelligent.board.utils.KeyboardThemeSaver
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 kotlinx.coroutines.launch
import java.io.File

class KeyboardSettingActivity : 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"
    }

    // 新增：声明tv_favorite控件
    private lateinit var tvFavorite: TextView

    // 进度条指示器相关
    private lateinit var progressIndicator: ProgressBar
    private var totalPageCount = 0

    private var dialog: KeyboardActivationDialog? = 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 recommendedViewPager: ViewPager2
    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 layoutFavoriteApply: LinearLayout
    private lateinit var data: KeyboardItemInfo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_keyboard_setting)
        this.enableEdgeToEdge()
        showTPAD(this) {}
        // 修复：优化父布局Insets处理
        ViewCompat.setOnApplyWindowInsetsListener(
            findViewById<View?>(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()
        // 修复：给ViewPager2单独设置Insets监听，避免高版本系统栏影响
        initViewPagerInsets()
        getExtraData()
        displayData()
        setApply()
        onClick()
        initRecommendedViewPager()
    }

    // 新增：ViewPager2的Insets适配
    private fun initViewPagerInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(recommendedViewPager) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())

            v.setPadding(systemBars.left, 0, systemBars.right, 0)
            insets
        }
    }

    private fun getExtraData() {
        data = intent.getSerializableExtra(SOURCE_KEY) as KeyboardItemInfo

        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 = KeyboardZipFileHandler.getServiceZipName(zipUrl)
        unzipPath = KeyboardZipFileHandler.getUnzipPath(serviceZipName)

        Log.d("-------------------", "-------unzipPath=" + unzipPath)
        lifecycleScope.launch {
            MyAppDatabaseManager.getIsLike(name) { isLiked ->
                // 核心修改：初始化时同步图标和文字状态
                imgLike.isSelected = isLiked
                updateFavoriteText(isLiked)
            }
        }

        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 findViewId() {
        applyBtn = findViewById(R.id.layoutDownloadApply)
        imgData = findViewById(R.id.image_data)
        imgBack = findViewById(R.id.back)
        textName = findViewById(R.id.textview_data_name)
        recommendedViewPager = findViewById(R.id.recommended_viewpager)
        imgLike = findViewById(R.id.im_like)
        layoutFavoriteApply = findViewById(R.id.layoutFavoriteApply)
        loadingLayout = findViewById(R.id.loading)
        imDownload = findViewById(R.id.im_download)
        tvDownload = findViewById(R.id.tv_download)
        // 核心修改：绑定tv_favorite控件
        tvFavorite = findViewById(R.id.tv_favorite)

        // 绑定进度条指示器
        progressIndicator = findViewById(R.id.progress_indicator)
    }

    private fun displayData() {
        textName.text = name
        if (gifUrl.isNotEmpty()) {
            loadImgGif()
        } else {
            Glide.with(this)
                .load(displayUrl)
                .thumbnail(Glide.with(this).load(thumb))
                .into(imgData)
        }
    }

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

        layoutFavoriteApply.setOnClickListener {
            val newState = !imgLike.isSelected
            imgLike.isSelected = newState
            // 核心修改：点击后同步文字状态
            updateFavoriteText(newState)

            lifecycleScope.launch {
                if (newState) {
                    MyAppDatabaseManager.addLike(data)
                } else {
                    MyAppDatabaseManager.removeLike(data)
                }
            }
        }
    }

    // 核心新增：统一更新Favorite文字的方法
    private fun updateFavoriteText(isLiked: Boolean) {
        tvFavorite.text = if (isLiked) {
            getString(R.string.favorite_apply_selected) // 选中时显示Favorited
        } else {
            getString(R.string.favorite_apply)  // 未选中时显示Favorite
        }
    }

    // 初始化ViewPager2 + 进度条指示器（修复最后一页进度）
    private fun initRecommendedViewPager() {
        val forYouList = AppContextHelper.list.filter {
            it.parentName == getString(R.string.recommend_name)
        }
        val allRecommendItems = forYouList[0].keyboardList.shuffled()

        // 计算总页数（2行2列，每页4个item）
        val itemsPerPage = 2 * 2
        totalPageCount = (allRecommendItems.size + itemsPerPage - 1) / itemsPerPage

        // 设置ViewPager2适配器
        recommendedViewPager.adapter = KeyboardItemAdapter(
            this,
            allRecommendItems,
            itemClickCallback = object : KeyboardItemClickListener {
                override fun OnItemClickListener() {
                    finish()
                }
            }
        )

        // 监听页面滑动，实时更新进度条（最后一页强制100%）
        recommendedViewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            // 页面滑动过程中（实时更新进度）
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                // 最后一页：强制进度100%
                if (position == totalPageCount - 1) {
                    progressIndicator.progress = 100
                    return
                }
                // 非最后一页：正常计算进度
                val totalProgress = ((position + positionOffset) / totalPageCount) * 100
                progressIndicator.progress = totalProgress.toInt()
            }

            // 页面选中后（校准进度）
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                // 最后一页：进度100%；其他页：按比例计算
                val progress = if (position == totalPageCount - 1) {
                    100
                } else {
                    ((position.toFloat() / totalPageCount) * 100).toInt()
                }
                progressIndicator.progress = progress
            }
        })

        // 初始化进度条（默认0%）
        progressIndicator.progress = 0
    }

    @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 {
            showTPAD(this) {
                val checkEnable = AppCommonUtils.checkEnable(this)
                val checkSetDefault = AppCommonUtils.checkSetDefault(this)
                if (!checkEnable || !checkSetDefault) {
                    showDialog()
                    return@showTPAD
                }
                startDown()
            }

        }
    }

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

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

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

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

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