package com.app.input.breeze.board.uiactivity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.app.input.breeze.board.App
import com.app.input.breeze.board.R
import com.app.input.breeze.board.bean.KeyboardTheme
import com.app.input.breeze.board.bean.CategoryWrapper
import com.app.input.breeze.board.databinding.MainActivityBinding
import com.app.input.breeze.board.listutils.QuickCategoryAdapter
import com.app.input.breeze.board.listutils.FeaturedThemeAdapter
import com.app.input.breeze.board.listutils.TrendingThemeAdapter

class MainActivity : AppCompatActivity() {

    private lateinit var vb: MainActivityBinding
    private lateinit var FeaturedThemeAdapter: FeaturedThemeAdapter
    private lateinit var QuickCategoryAdapter: QuickCategoryAdapter
    private lateinit var TrendingThemeAdapter: TrendingThemeAdapter
    private lateinit var newAdapter: TrendingThemeAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = MainActivityBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(vb.root)
        
        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
        }

        initViews()
        setupHero()
        setupQuickCategories()
        setupTrending()
        setupNew()
        setupClickListeners()
        setupBottomNavigation()
    }

    private fun initViews() {
        // Hero 区域 - 横向滑动，每次滑动显示一张完整卡片
        val heroLayoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        vb.heroRecycler.layoutManager = heroLayoutManager
        vb.heroRecycler.isNestedScrollingEnabled = false
        
        // 使用 PagerSnapHelper 实现每次滑动对齐到一张完整卡片
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(vb.heroRecycler)
        
        // 快速分类 - 横向滑动
        vb.quickCategoryRecycler.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        
        // Trending - 横向滑动
        vb.trendingRecycler.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        
        // New - 横向滑动
        vb.newRecycler.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
    }

    /**
     * 设置 Hero 区域 - 今日精选键盘
     * 固定显示三个指定的精选主题，支持横向滑动
     */
    private fun setupHero() {
        val heroList = mutableListOf<KeyboardTheme>()
        
        // 固定的三个精选主题名称
        val featuredThemeNames = listOf(
            "Gravity Water Ice",
            "Snowflake Gravity",
            "Pastel Clouds Sky"
        )
        
        // 从所有分类中查找这三个主题
        val allThemes = mutableListOf<KeyboardTheme>()
        App.list.forEach { wrapper ->
            allThemes.addAll(wrapper.keyboardList)
        }
        
        // 按照指定顺序查找并添加主题
        featuredThemeNames.forEach { themeName ->
            val theme = allThemes.find { it.titleName == themeName }
            if (theme != null) {
                heroList.add(theme)
            }
        }

        FeaturedThemeAdapter = FeaturedThemeAdapter(this, heroList) { KeyboardTheme ->
            navigateToDetail(KeyboardTheme)
        }
        
        // 设置 adapter 并立即刷新
        vb.heroRecycler.adapter = FeaturedThemeAdapter
        
        // 确保 RecyclerView 可见
        if (vb.heroRecycler.visibility != View.VISIBLE) {
            vb.heroRecycler.visibility = View.VISIBLE
        }
        
        // 立即通知数据变化
        FeaturedThemeAdapter.notifyDataSetChanged()
        
        // 强制请求布局，确保立即显示
        vb.heroRecycler.requestLayout()
        
        // 设置指示器
        setupHeroIndicator(heroList.size)
        
        // 初始化指示器状态
        vb.heroRecycler.post {
            updateHeroIndicator()
        }
        
        // 监听滚动状态变化，在滑动结束时更新指示器
        vb.heroRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                // 当滑动停止时更新指示器
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateHeroIndicator()
                }
            }
            
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 滑动过程中也更新，但主要依赖 SCROLL_STATE_IDLE
            }
        })
    }
    
    /**
     * 设置 Hero 指示器
     */
    private fun setupHeroIndicator(count: Int) {
        vb.heroIndicatorContainer.removeAllViews()
        
        for (i in 0 until count) {
            val indicator = View(this).apply {
                layoutParams = android.widget.LinearLayout.LayoutParams(
                    resources.getDimensionPixelSize(android.R.dimen.app_icon_size) / 4,
                    resources.getDimensionPixelSize(android.R.dimen.app_icon_size) / 4
                ).apply {
                    if (i > 0) {
                        marginStart = resources.getDimensionPixelSize(android.R.dimen.app_icon_size) / 8
                    }
                }
                background = if (i == 0) {
                    resources.getDrawable(R.drawable.dot_indicator_selected, theme)
                } else {
                    resources.getDrawable(R.drawable.dot_indicator, theme)
                }
            }
            vb.heroIndicatorContainer.addView(indicator)
        }
    }
    
    /**
     * 更新 Hero 指示器状态
     */
    private fun updateHeroIndicator() {
        val layoutManager = vb.heroRecycler.layoutManager as? LinearLayoutManager ?: return
        
        // 使用 PagerSnapHelper 后，findFirstCompletelyVisibleItemPosition 更准确
        val currentPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
        
        // 如果找不到完全可见的，使用第一个可见的
        val position = if (currentPosition != RecyclerView.NO_POSITION) {
            currentPosition
        } else {
            layoutManager.findFirstVisibleItemPosition().coerceAtLeast(0)
        }.coerceIn(0, vb.heroIndicatorContainer.childCount - 1)
        
        // 更新指示器状态
        for (i in 0 until vb.heroIndicatorContainer.childCount) {
            val indicator = vb.heroIndicatorContainer.getChildAt(i)
            indicator.background = if (i == position) {
                resources.getDrawable(R.drawable.dot_indicator_selected, theme)
            } else {
                resources.getDrawable(R.drawable.dot_indicator, theme)
            }
        }
    }

    /**
     * 设置快速分类入口
     * 显示圆形/胶囊按钮，只是入口，不展示内容
     * 使用实际数据中存在的分类名称
     */
    private fun setupQuickCategories() {
        // 快速分类列表：显示名称 -> (实际分类名称, emoji)
        // 根据实际数据中的分类：recommend, aesthetic, cool, cute, festival, live, love, neon, gravity, super theme
        // 为每个分类选择更匹配的emoji图标
        val categoryData = listOf(
            Triple("Cute", "cute", "💖"),           // 粉色爱心 - 可爱
            Triple("Neon", "neon", "🌌"),          // 银河 - 霓虹
            Triple("Cool", "cool", "😎"),          // 墨镜笑脸 - 酷
            Triple("Aesthetic", "aesthetic", "✨"), // 星星 - 美学
            Triple("Love", "love", "💕"),          // 粉色爱心 - 爱情
            Triple("Gravity", "gravity", "🌍")     // 地球 - 重力
        )
        
        // 创建显示列表（名称, emoji）
        val categories = categoryData.map { it.first to it.third }
        
        // 创建映射关系（显示名称 -> 实际分类名称）
        val categoryMapping = categoryData.associate { it.first to it.second }

        QuickCategoryAdapter = QuickCategoryAdapter(this, categories) { displayName ->
            // 根据显示名称找到对应的实际分类名称
            val actualCategoryName = categoryMapping[displayName] ?: displayName.lowercase()
            // 跳转到分类详情页
            navigateToCategory(actualCategoryName)
        }
        vb.quickCategoryRecycler.adapter = QuickCategoryAdapter
    }

    /**
     * 设置 Trending 推荐
     * 从 recommend 分类获取数据，横向滑动
     */
    private fun setupTrending() {
        val trendingList = mutableListOf<KeyboardTheme>()
        
        val recommendWrapper = App.list.find { it.parentName == "recommend" }
        recommendWrapper?.keyboardList?.take(10)?.let {
            trendingList.addAll(it)
        }

        TrendingThemeAdapter = TrendingThemeAdapter(this, trendingList) { KeyboardTheme ->
            navigateToDetail(KeyboardTheme)
        }
        vb.trendingRecycler.adapter = TrendingThemeAdapter
    }

    /**
     * 设置 New 推荐
     * 从除了 recommend 之外的其他分类中混合获取主题
     */
    private fun setupNew() {
        val newList = mutableListOf<KeyboardTheme>()
        
        // 从所有分类中收集主题（排除 recommend）
        val otherCategories = App.list.filter { 
            it.parentName != "recommend" 
        }
        
        // 从多个分类中混合获取主题，每个分类取前几个
        otherCategories.forEachIndexed { index, wrapper ->
            if (index < 3 && newList.size < 10) { // 最多从3个分类获取，总共不超过10个
                val takeCount = (10 - newList.size).coerceAtMost(4) // 每个分类最多取4个
                wrapper.keyboardList.take(takeCount).let {
                    newList.addAll(it)
                }
            }
        }
        
        // 如果还是没有数据，从第一个非 recommend 分类获取
        if (newList.isEmpty() && App.list.size > 1) {
            App.list.find { it.parentName != "recommend" }?.keyboardList?.take(10)?.let {
                newList.addAll(it)
            }
        }
        
        // 打乱顺序，让不同分类的主题混合显示
        val shuffled = newList.shuffled()

        newAdapter = TrendingThemeAdapter(this, shuffled) { KeyboardTheme ->
            navigateToDetail(KeyboardTheme)
        }
        vb.newRecycler.adapter = newAdapter
    }

    private fun setupClickListeners() {
        // 跳转到收藏页面
        vb.btnFavorite.setOnClickListener {
            startActivity(Intent(this, FavoriteThemeActivity::class.java))
        }
    }

    private fun setupBottomNavigation() {
        // 设置默认选中主页
        updateBottomNavState(R.id.nav_home)

        // 主页点击
        findViewById<View>(R.id.nav_home).setOnClickListener {
            // 已经在主页，不需要操作
            updateBottomNavState(R.id.nav_home)
        }

        // 分类点击
        findViewById<View>(R.id.nav_category).setOnClickListener {
            startActivity(Intent(this, CategoryScreen::class.java))
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            finish()
        }

        // 设置点击
        findViewById<View>(R.id.nav_settings).setOnClickListener {
            startActivity(Intent(this, SettingsScreen::class.java))
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
        }
    }

    private fun updateBottomNavState(selectedId: Int) {
        val selectedColor = getColor(R.color.blue_primary)
        val unselectedColor = 0x80000000.toInt()

        // 重置所有状态
        val homeIcon = findViewById<android.widget.ImageView>(R.id.nav_home_icon)
        val homeText = findViewById<android.widget.TextView>(R.id.nav_home_text)
        val homeIndicator = findViewById<View>(R.id.nav_home_indicator)
        val categoryIcon = findViewById<android.widget.ImageView>(R.id.nav_category_icon)
        val categoryText = findViewById<android.widget.TextView>(R.id.nav_category_text)
        val categoryIndicator = findViewById<View>(R.id.nav_category_indicator)
        val settingsIcon = findViewById<android.widget.ImageView>(R.id.nav_settings_icon)
        val settingsText = findViewById<android.widget.TextView>(R.id.nav_settings_text)
        val settingsIndicator = findViewById<View>(R.id.nav_settings_indicator)

        when (selectedId) {
            R.id.nav_home -> {
                homeIcon.setColorFilter(selectedColor)
                homeText.setTextColor(selectedColor)
                homeIndicator.visibility = View.VISIBLE
                categoryIcon.setColorFilter(unselectedColor)
                categoryText.setTextColor(unselectedColor)
                categoryIndicator.visibility = View.GONE
                settingsIcon.setColorFilter(unselectedColor)
                settingsText.setTextColor(unselectedColor)
                settingsIndicator.visibility = View.GONE
            }
            R.id.nav_category -> {
                homeIcon.setColorFilter(unselectedColor)
                homeText.setTextColor(unselectedColor)
                homeIndicator.visibility = View.GONE
                categoryIcon.setColorFilter(selectedColor)
                categoryText.setTextColor(selectedColor)
                categoryIndicator.visibility = View.VISIBLE
                settingsIcon.setColorFilter(unselectedColor)
                settingsText.setTextColor(unselectedColor)
                settingsIndicator.visibility = View.GONE
            }
            R.id.nav_settings -> {
                homeIcon.setColorFilter(unselectedColor)
                homeText.setTextColor(unselectedColor)
                homeIndicator.visibility = View.GONE
                categoryIcon.setColorFilter(unselectedColor)
                categoryText.setTextColor(unselectedColor)
                categoryIndicator.visibility = View.GONE
                settingsIcon.setColorFilter(selectedColor)
                settingsText.setTextColor(selectedColor)
                settingsIndicator.visibility = View.VISIBLE
            }
        }
    }

    private fun navigateToDetail(KeyboardTheme: KeyboardTheme) {
        val intent = Intent(this, ThemeDetailActivity::class.java).apply {
            putExtra(ThemeDetailActivity.SOURCE_KEY, KeyboardTheme)
            putExtra(ThemeDetailActivity.DISPLAY_URL_KEY, KeyboardTheme.imgPath)
            putExtra(ThemeDetailActivity.ZIP_URL_KEY, KeyboardTheme.zipPath)
            putExtra(ThemeDetailActivity.NAME_KEY, KeyboardTheme.titleName)
            putExtra(ThemeDetailActivity.GIF_KEY, KeyboardTheme.imgGif)
            val thumbGif = KeyboardTheme.thumbGif
            val thumb = if (thumbGif != null && thumbGif.isNotEmpty()) {
                thumbGif
            } else {
                KeyboardTheme.thumbUrl
            }
            putExtra(ThemeDetailActivity.THUMB_KEY, thumb)
        }
        startActivity(intent)
    }

    private fun navigateToCategory(categoryName: String) {
        // 查找对应的分类（精确匹配，不区分大小写）
        val categoryWrapper = App.list.find { 
            it.parentName.equals(categoryName, ignoreCase = true)
        }
        
        if (categoryWrapper != null) {
            val intent = Intent(this, ThemeListActivity::class.java).apply {
                putExtra(ThemeListActivity.KEY_NAME, categoryWrapper.parentName)
            }
            startActivity(intent)
        } else {
            // 如果找不到，跳转到分类页面（让用户自己选择）
            startActivity(Intent(this, CategoryScreen::class.java))
        }
    }
}

