package com.app.wave.keyboard.ui

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.wave.keyboard.App
import com.app.wave.keyboard.bean.WrapperBean
import com.app.wave.keyboard.databinding.FragmentHomepageBinding
import com.app.wave.keyboard.callback.MoreCallback
import com.app.wave.keyboard.adapter.CategoryAdapter

class HomepageFragment : Fragment() {

    private var binding: FragmentHomepageBinding? = null
    private lateinit var viewAllList: MutableList<WrapperBean>
    private lateinit var adapterParent: CategoryAdapter
    private var scrollListener: OnScrollListener? = null

    companion object {
        @JvmStatic
        fun newInstance() = HomepageFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val vb = FragmentHomepageBinding.inflate(inflater, container, false)
        binding = vb
        return vb.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        setupRecyclerView()
        setupClickListeners()
        setupScrollListener()
    }

    private fun initViews() {
        binding?.let { vb ->
            vb.appName.typeface = Typeface.create(vb.appName.typeface, Typeface.BOLD)
        }
    }

    private fun setupRecyclerView() {
        viewAllList = App.Companion.list
        adapterParent = CategoryAdapter(
            requireContext(), viewAllList
        ).apply {
            setClickAction(object : MoreCallback {
                override fun OnClickSeeAll(name: String) {
                    startActivity(Intent(requireContext(),
                        MoreActivity::class.java).apply {
                        putExtra(MoreActivity.KEY_NAME, name)
                    })
                }
            })
        }

        binding?.let { vb ->
            vb.recyclerview.run {
                adapter = adapterParent
                layoutManager = LinearLayoutManager(requireContext())

                // 添加垂直间距装饰器
                if (itemDecorationCount == 0) {
                    addItemDecoration(VerticalSpaceItemDecoration(
                        topSpacing = 0,  // 第一个item顶部不需要间距
                        betweenSpacing = 11.dpToPx(requireContext()),  // item之间的间距
                        bottomSpacing = 4.dpToPx(requireContext())  // 每个item的底部间距
                    ))
                }
            }
        }
    }

    // 简单的垂直间距装饰器
    class VerticalSpaceItemDecoration(
        private val topSpacing: Int = 0,
        private val betweenSpacing: Int = 0,
        private val bottomSpacing: Int = 0
    ) : RecyclerView.ItemDecoration() {

        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            super.getItemOffsets(outRect, view, parent, state)

            val position = parent.getChildAdapterPosition(view)
            val itemCount = state.itemCount

            if (position == 0) {
                // 第一个item
                outRect.top = topSpacing
                outRect.bottom = betweenSpacing
            } else if (position == itemCount - 1) {
                // 最后一个item
                outRect.top = betweenSpacing
                outRect.bottom = bottomSpacing
            } else {
                // 中间的item
                outRect.top = betweenSpacing
                outRect.bottom = betweenSpacing
            }
        }
    }

    // dp转px的扩展函数
    private fun Int.dpToPx(context: Context): Int {
        return (this * context.resources.displayMetrics.density).toInt()
    }

    private fun setupClickListeners() {
        binding?.let { vb ->
            // 回到顶部按钮点击事件
            vb.btnScrollToTop.setOnClickListener {
                scrollToTop()
            }

            // 应用图标点击事件（回到顶部）
            vb.appIcon.setOnClickListener {
                scrollToTop()
            }

            // 收藏图标点击事件 - 修改为跳转到设置页面
            vb.collectionIcon.setOnClickListener {
                openSettingActivity()
            }
        }
    }

    private fun openSettingActivity() {
        try {
            val intent = Intent(requireContext(), SettingsActivity::class.java)
            startActivity(intent)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }
    }

    private fun setupScrollListener() {
        binding?.let { vb ->
            vb.recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)

                    // 检查是否可以向上滚动
                    val canScrollUp = recyclerView.canScrollVertically(-1)
                    vb.btnScrollToTop.visibility = if (canScrollUp) View.VISIBLE else View.GONE

                    // 通知外部滚动监听器
                    scrollListener?.onScroll(canScrollUp)
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)

                    // 滚动停止时检查一次，确保状态正确
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        val canScrollUp = recyclerView.canScrollVertically(-1)
                        vb.btnScrollToTop.visibility = if (canScrollUp) View.VISIBLE else View.GONE
                    }
                }
            })

            // 初始检查一次，如果一开始就可以向上滚动，就显示按钮
            vb.recyclerview.post {
                val canScrollUp = vb.recyclerview.canScrollVertically(-1)
                vb.btnScrollToTop.visibility = if (canScrollUp) View.VISIBLE else View.GONE
            }
        }
    }

    private fun scrollToTop() {
        binding?.let { vb ->
            if (vb.recyclerview.layoutManager != null) {
                // 平滑滚动到顶部
                vb.recyclerview.smoothScrollToPosition(0)
                // 滚动结束后会触发onScrolled，按钮会自动隐藏
            }
        }
    }

    // 提供一个公共方法供外部调用滚动到顶部
    fun scrollToTopFromOutside() {
        scrollToTop()
    }

    // 检查是否可以向上滚动（用于外部调用）
    fun canScrollUp(): Boolean {
        return binding?.recyclerview?.canScrollVertically(-1) ?: false
    }

    // 检查当前滚动状态（用于外部调用）
    fun checkCurrentScrollState() {
        val canScrollUp = canScrollUp()
        scrollListener?.onScroll(canScrollUp)
    }

    // 滚动监听器接口
    interface OnScrollListener {
        fun onScroll(canScrollUp: Boolean)
    }

    // 设置滚动监听器
    fun setOnScrollListener(listener: OnScrollListener) {
        this.scrollListener = listener
        // 立即检查当前状态并通知
        checkCurrentScrollState()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
        scrollListener = null
    }
}