package com.led.scroller.barrage.banner.ui

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.ComponentCaller
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.animation.LinearInterpolator
import androidx.activity.enableEdgeToEdge
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import com.ad.tradpluslibrary.TPAdManager
import com.led.scroller.barrage.banner.R
import com.led.scroller.barrage.banner.databinding.ActivityMainBinding
import com.led.scroller.barrage.banner.sp.AppSP
import com.led.scroller.barrage.banner.ui.adapter.TabFragmentPagerAdapter

class MainActivity : BaseActivity(), TextFragment.TextFragmentClickListener,
    BackgroundFragment.BackgroundFragmentClickListener {
    private var animSet: AnimatorSet? = null
    private var animOne: ObjectAnimator? = null
    private lateinit var binding: ActivityMainBinding
    private var mFragments: MutableList<Fragment> = mutableListOf()
    private var mStrings: MutableList<String> = mutableListOf()
    private lateinit var tabFragmentPagerAdapter: TabFragmentPagerAdapter
    private val textFragment = TextFragment()
    private val backgroundFragment = BackgroundFragment()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        immersionBar()
        initView()
        initTab()
        animatorRightToLeft()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.d("MainActivity", "onSaveInstanceState")
    }

    private fun immersionBar() {
        //自适应沉浸式
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = false//状态栏文字颜色
    }

    private fun initTab() {
        mStrings.add(getString(R.string.text))
        mStrings.add(getString(R.string.background))
        mFragments.add(textFragment)
        mFragments.add(backgroundFragment)

        tabFragmentPagerAdapter =
            TabFragmentPagerAdapter(supportFragmentManager, mFragments, mStrings)
        binding.viewPager.adapter = tabFragmentPagerAdapter
        binding.tabLayout.setupWithViewPager(binding.viewPager)

        // 设置页面变化监听器，确保Fragment在显示时正确设置监听器
        binding.viewPager.addOnPageChangeListener(object :
            androidx.viewpager.widget.ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                Log.d("MainActivity", "页面被选中: $position")
                // 当页面被选中时，确保监听器已设置
                val fragment =
                    supportFragmentManager.findFragmentByTag("android:switcher:${binding.viewPager.id}:$position")
                Log.d("MainActivity", "找到的Fragment: $fragment")
                when (fragment) {
                    is TextFragment -> {
                        Log.d("MainActivity", "设置TextFragment监听器（页面切换）")
                        fragment.setTextFragmentClickListener(this@MainActivity)
                    }
                    is BackgroundFragment -> {
                        Log.d("MainActivity", "设置BackgroundFragment监听器（页面切换）")
                        fragment.setBackgroundFragmentClickListener(this@MainActivity)
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        //屏蔽事件
        binding.horizontalScrollview.setOnTouchListener { v, _ ->
            v.parent.requestDisallowInterceptTouchEvent(true)
            true
        }
        binding.startBtn.setOnClickListener {
            val content = binding.contentEdit.text.toString()
            if (content.isNotEmpty()) {

                TPAdManager.showTPAD(this@MainActivity){
                    val intent = Intent(this, ShowBarrageActivity::class.java)
                    intent.putExtra(ShowBarrageActivity.CONTENT_KEY, content)
                    startActivity(intent)
                }

            } else {
                showToast(getString(R.string.type_something))
            }
        }
        binding.contentEdit.addTextChangedListener {
            updatePreviewText()
        }
    }

    private var content = ""
    private fun updatePreviewText() {
        content = binding.contentEdit.text.toString()
        val sp = AppSP(this)
        binding.previewLayout.setBackgroundColor(getColor(sp.bgColorResId))
        binding.previewText.text = content
        binding.previewText.setTextColor(getColor(sp.fontColorResId))
        binding.previewText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, sp.fontSize.toFloat())
        val typeface = ResourcesCompat.getFont(this, sp.fontResId)
        binding.previewText.typeface = typeface
    }

    private fun animatorRightToLeft() {
        val textPaint = binding.previewText.paint
        val textPaintWidth = textPaint.measureText(content) //获取文字的宽度。
        val screenWidth = resources.displayMetrics.widthPixels //获取屏幕的宽度。
        animSet = AnimatorSet()
        animSet?.interpolator = LinearInterpolator() //线性
        animOne = ObjectAnimator.ofFloat(
            binding.previewText,
            "translationX",
            screenWidth.toString().toFloat(),
            -textPaintWidth
        ) //X轴移动，屏幕宽度为起始值，也就是会从最右边开始到看不到文字。
        animOne?.duration = 5000
        animOne?.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                animatorRightToLeft()
            }
        })
        animSet?.play(animOne)
        animSet?.start()
    }

    override fun onPause() {
        super.onPause()
        pauseAnimation()
    }

    override fun onResume() {
        super.onResume()
        Log.d("MainActivity", "onResume()被调用")
        resumeAnimation()
        updatePreviewText()
        
        // 延迟重置监听器，确保Fragment完全恢复
        binding.viewPager.post {
            Log.d("MainActivity", "延迟重置Fragment监听器")
            resetFragmentListeners()
            
            // 强制重新创建适配器作为最后手段
            if (tabFragmentPagerAdapter != null) {
                Log.d("MainActivity", "重新创建适配器")
                tabFragmentPagerAdapter = TabFragmentPagerAdapter(supportFragmentManager, mFragments, mStrings)
                binding.viewPager.adapter = tabFragmentPagerAdapter
                binding.tabLayout.setupWithViewPager(binding.viewPager)
                
                // 重新设置监听器
                binding.viewPager.postDelayed({
                    resetFragmentListeners()
                }, 100)
            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        Log.d("MainActivity", "onRestart()被调用")
    }

    override fun onStart() {
        super.onStart()
        Log.d("MainActivity", "onStart()被调用")
    }

    private fun resetFragmentListeners() {
        Log.d("MainActivity", "开始重置Fragment监听器")
        
        // 方法1：尝试通过ViewPager获取当前Fragment实例
        val currentTextFragment = supportFragmentManager.findFragmentByTag("android:switcher:${binding.viewPager.id}:0") as? TextFragment
        val currentBackgroundFragment = supportFragmentManager.findFragmentByTag("android:switcher:${binding.viewPager.id}:1") as? BackgroundFragment
        
        Log.d("MainActivity", "当前TextFragment实例: $currentTextFragment, 保存的实例: $textFragment")
        Log.d("MainActivity", "当前BackgroundFragment实例: $currentBackgroundFragment, 保存的实例: $backgroundFragment")
        
        // 方法2：设置到当前活动的Fragment实例
        currentTextFragment?.let { fragment ->
            Log.d("MainActivity", "设置当前TextFragment监听器")
            fragment.setTextFragmentClickListener(this)
        }
        
        currentBackgroundFragment?.let { fragment ->
            Log.d("MainActivity", "设置当前BackgroundFragment监听器")
            fragment.setBackgroundFragmentClickListener(this)
        }
        
        // 方法3：同时设置到保存的实例（作为备份）
        textFragment.setTextFragmentClickListener(this)
        backgroundFragment.setBackgroundFragmentClickListener(this)
        
        // 方法4：强制刷新ViewPager的当前页面
        val currentItem = binding.viewPager.currentItem
        if (currentItem == 0) {
            currentTextFragment?.setTextFragmentClickListener(this)
        } else if (currentItem == 1) {
            currentBackgroundFragment?.setBackgroundFragmentClickListener(this)
        }
        
        Log.d("MainActivity", "Fragment监听器重置完成")
    }

    private fun pauseAnimation() {
        animSet?.pause()
    }

    private fun resumeAnimation() {
        animSet?.resume()
    }

    override fun onFontItemClick() {
        Log.d("MainActivity", "收到onFontItemClick回调")
        updatePreviewText()
    }

    override fun onFontColorItemClick() {
        Log.d("MainActivity", "收到onFontColorItemClick回调")
        updatePreviewText()
    }

    override fun onFontSizeItemClick() {
        Log.d("MainActivity", "收到onFontSizeItemClick回调")
        updatePreviewText()
    }

    override fun onBgColorClick() {
        Log.d("MainActivity", "收到onBgColorClick回调")
        updatePreviewText()
    }
}