package com.narutohuo.xindazhou.common.launch.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.button.MaterialButton
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.narutohuo.xindazhou.common.R
import com.narutohuo.xindazhou.common.auth.NavigationCallback
import com.narutohuo.xindazhou.common.launch.OnboardingManager
import com.narutohuo.xindazhou.common.launch.model.OnboardingItem

/**
 * 引导页 Fragment
 * 
 * 首次安装后显示的引导页，用户可以滑动浏览多张引导图片
 * 最后一页有"立即体验"按钮，点击后进入主界面或登录页
 * 
 * 使用方式：
 * ```kotlin
 * // 使用默认引导页数据
 * val fragment = OnboardingFragment()
 * 
 * // 或者自定义引导页数据
 * val fragment = OnboardingFragment()
 * fragment.setOnboardingItems(listOf(
 *     OnboardingItem(title = "标题1", description = "描述1"),
 *     OnboardingItem(title = "标题2", description = "描述2")
 * ))
 * ```
 */
open class OnboardingFragment : Fragment() {
    
    private lateinit var viewPager: ViewPager2
    private lateinit var tabIndicator: TabLayout
    private lateinit var btnStart: MaterialButton
    private lateinit var btnSkip: MaterialButton
    
    private val navigationCallback: NavigationCallback?
        get() = activity as? NavigationCallback
    
    // 默认引导页数据（可以在 app 模块中通过方法注入自定义数据）
    private var onboardingItems: List<OnboardingItem> = emptyList()
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_onboarding, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        viewPager = view.findViewById(R.id.viewPager)
        tabIndicator = view.findViewById(R.id.tabIndicator)
        btnStart = view.findViewById(R.id.btnStart)
        btnSkip = view.findViewById(R.id.btnSkip)
        
        // 如果子类没有提供数据，使用默认数据
        if (onboardingItems.isEmpty()) {
            onboardingItems = getDefaultOnboardingItems()
        }
        
        // 设置 ViewPager2 适配器
        val adapter = OnboardingPagerAdapter(onboardingItems)
        viewPager.adapter = adapter
        
        // 连接 TabLayout 和 ViewPager2
        TabLayoutMediator(tabIndicator, viewPager) { _, _ -> }.attach()
        
        // 初始化按钮显示状态（第一页显示"跳过"按钮）
        updateButtonVisibility(0)
        
        // 监听页面变化，在最后一页显示"立即体验"按钮
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateButtonVisibility(position)
            }
        })
        
        // "立即体验"按钮点击事件
        btnStart.setOnClickListener {
            finishOnboarding()
        }
        
        // "跳过"按钮点击事件
        btnSkip.setOnClickListener {
            finishOnboarding()
        }
    }
    
    /**
     * 更新按钮显示状态
     */
    private fun updateButtonVisibility(position: Int) {
        // 如果是最后一页，显示"立即体验"按钮，隐藏"跳过"按钮
        if (position == onboardingItems.size - 1) {
            btnStart.visibility = View.VISIBLE
            btnSkip.visibility = View.GONE
        } else {
            btnStart.visibility = View.GONE
            btnSkip.visibility = View.VISIBLE
        }
    }
    
    /**
     * 完成引导页，标记已看过并导航到下一步
     */
    private fun finishOnboarding() {
        // 标记已经看过引导页
        OnboardingManager.markOnboardingAsSeen()
        
        // 通过接口回调触发导航（由 MainActivity 处理具体导航逻辑）
        // MainActivity 会根据登录状态导航到登录页或主界面
        navigationCallback?.navigateToLogin()
    }
    
    /**
     * 设置引导页数据（可选，子类可以调用此方法设置自定义数据）
     */
    fun setOnboardingItems(items: List<OnboardingItem>) {
        this.onboardingItems = items
        // 如果 ViewPager 已经创建，更新适配器
        if (::viewPager.isInitialized && viewPager.adapter != null) {
            (viewPager.adapter as? OnboardingPagerAdapter)?.updateItems(items)
        }
    }
    
    /**
     * 获取默认引导页数据
     * 
     * 子类可以重写此方法提供自定义的引导页数据
     */
    protected open fun getDefaultOnboardingItems(): List<OnboardingItem> {
        return listOf(
            OnboardingItem(
                title = "欢迎使用新大洲本田",
                description = "探索更多精彩功能，开启您的智能出行体验"
            ),
            OnboardingItem(
                title = "智能车辆管理",
                description = "实时查看车辆状态，轻松管理您的爱车"
            ),
            OnboardingItem(
                title = "便捷服务",
                description = "一键预约维修、保养等服务，让用车更简单"
            )
        )
    }
    
    /**
     * ViewPager2 适配器
     */
    private class OnboardingPagerAdapter(
        private var items: List<OnboardingItem>
    ) : RecyclerView.Adapter<OnboardingPagerAdapter.ViewHolder>() {
        
        fun updateItems(newItems: List<OnboardingItem>) {
            items = newItems
            notifyDataSetChanged()
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_onboarding, parent, false)
            return ViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = items[position]
            holder.bind(item)
        }
        
        override fun getItemCount(): Int = items.size
        
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val ivImage: ImageView = itemView.findViewById(R.id.ivImage)
            private val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
            private val tvDescription: TextView = itemView.findViewById(R.id.tvDescription)
            
            fun bind(item: OnboardingItem) {
                tvTitle.text = item.title
                tvDescription.text = item.description
                
                // 设置图片（如果有）
                if (item.imageResId != null) {
                    ivImage.setImageResource(item.imageResId)
                    ivImage.visibility = View.VISIBLE
                } else if (!item.imageUrl.isNullOrEmpty()) {
                    // 使用图片加载库加载网络图片（这里需要根据项目使用的图片加载库来实现）
                    // 例如使用 Glide: Glide.with(ivImage).load(item.imageUrl).into(ivImage)
                    ivImage.visibility = View.VISIBLE
                } else {
                    // 没有图片时隐藏 ImageView
                    ivImage.visibility = View.GONE
                }
            }
        }
    }
}

