package com.narutohuo.xindazhou.common.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * 级联选择器对话框
 * 
 * 支持多级联动选择，类似 iOS 的滚轮选择器
 * 
 * 使用方式：
 * ```kotlin
 * // 二级联动
 * val data = listOf(
 *     CascadeData("北京", listOf("东城区", "西城区", "朝阳区")),
 *     CascadeData("上海", listOf("黄浦区", "徐汇区", "长宁区"))
 * )
 * CascadePickerDialog.show(context, data) { selected ->
 *     // selected 是选中的路径，如 ["北京", "朝阳区"]
 * }
 * ```
 */
object CascadePickerDialog {
    
    /**
     * 级联数据模型
     */
    data class CascadeData(
        val label: String,
        val children: List<CascadeData>? = null,
        val value: Any? = null  // 可选的值对象
    )
    
    /**
     * 显示级联选择器
     * 
     * @param context 上下文
     * @param data 级联数据列表
     * @param title 标题（可选）
     * @param onConfirm 确认回调，返回选中的路径数组
     * @param onCancel 取消回调（可选）
     */
    fun show(
        context: Context,
        data: List<CascadeData>,
        title: String? = null,
        onConfirm: ((List<String>) -> Unit)? = null,
        onCancel: (() -> Unit)? = null
    ): Dialog {
        return createDialog(context, data, title, onConfirm, onCancel)
    }
    
    /**
     * 显示级联选择器（Activity 扩展函数）
     */
    fun Activity.showCascadePicker(
        data: List<CascadeData>,
        title: String? = null,
        onConfirm: ((List<String>) -> Unit)? = null,
        onCancel: (() -> Unit)? = null
    ): Dialog {
        return show(this, data, title, onConfirm, onCancel)
    }
    
    /**
     * 显示级联选择器（Fragment 扩展函数）
     */
    fun Fragment.showCascadePicker(
        data: List<CascadeData>,
        title: String? = null,
        onConfirm: ((List<String>) -> Unit)? = null,
        onCancel: (() -> Unit)? = null
    ): Dialog {
        return show(requireContext(), data, title, onConfirm, onCancel)
    }
    
    /**
     * 创建级联选择器对话框
     */
    private fun createDialog(
        context: Context,
        data: List<CascadeData>,
        title: String?,
        onConfirm: ((List<String>) -> Unit)?,
        onCancel: (() -> Unit)?
    ): Dialog {
        val dialog = Dialog(context)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.window?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            setGravity(Gravity.BOTTOM)
        }
        
        // 创建主容器
        val container = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            setBackgroundColor(Color.WHITE)
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        
        // 标题栏
        val titleBar = LinearLayout(context).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(0, dpToPx(context, 16f), 0, dpToPx(context, 16f))
            gravity = Gravity.CENTER_VERTICAL
        }
        
        // 取消按钮
        val cancelButton = TextView(context).apply {
            text = "取消"
            textSize = 16f
            setTextColor(Color.parseColor("#007AFF"))
            setPadding(dpToPx(context, 16f), 0, dpToPx(context, 16f), 0)
            setOnClickListener {
                dialog.dismiss()
                onCancel?.invoke()
            }
        }
        titleBar.addView(cancelButton)
        
        // 标题
        if (!title.isNullOrEmpty()) {
            val titleView = TextView(context).apply {
                this.text = title
                textSize = 17f
                setTextColor(Color.parseColor("#000000"))
                setTypeface(null, android.graphics.Typeface.BOLD)
                layoutParams = LinearLayout.LayoutParams(
                    0,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    1f
                )
                gravity = Gravity.CENTER
            }
            titleBar.addView(titleView)
        } else {
            // 占位
            val placeholder = View(context).apply {
                layoutParams = LinearLayout.LayoutParams(
                    0,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    1f
                )
            }
            titleBar.addView(placeholder)
        }
        
        // 级联选择器视图（先创建，以便在确定按钮中使用）
        val pickerView = CascadePickerView(context, data)
        
        // 确定按钮
        val confirmButton = TextView(context).apply {
            text = "确定"
            textSize = 16f
            setTextColor(Color.parseColor("#007AFF"))
            setPadding(dpToPx(context, 16f), 0, dpToPx(context, 16f), 0)
            setOnClickListener {
                // 获取选中的路径
                val selected = pickerView.getSelectedPath()
                dialog.dismiss()
                onConfirm?.invoke(selected)
            }
        }
        titleBar.addView(confirmButton)
        
        container.addView(titleBar)
        
        // 分隔线
        val divider = View(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                dpToPx(context, 1f)
            )
            setBackgroundColor(Color.parseColor("#E5E5EA"))
        }
        container.addView(divider)
        container.addView(pickerView, LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            dpToPx(context, 200f)
        ))
        
        dialog.setContentView(container)
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        
        return dialog
    }
    
    /**
     * 级联选择器视图
     */
    private class CascadePickerView(
        context: Context,
        private val data: List<CascadeData>
    ) : LinearLayout(context) {
        
        private val recyclerViews = mutableListOf<RecyclerView>()
        private val adapters = mutableListOf<CascadeAdapter>()
        private var currentLevel = 0
        private val selectedPath = mutableListOf<String>()
        
        init {
            orientation = LinearLayout.HORIZONTAL
            setupLevel(0, data)
        }
        
        /**
         * 设置选择级别
         */
        private fun setupLevel(level: Int, items: List<CascadeData>) {
            // 移除多余的级别
            while (recyclerViews.size > level + 1) {
                removeView(recyclerViews.removeAt(recyclerViews.size - 1))
                adapters.removeAt(adapters.size - 1)
            }
            
            // 如果当前级别已存在，更新数据
            if (level < recyclerViews.size) {
                adapters[level].updateData(items)
            } else {
                // 创建新的级别
                val recyclerView = RecyclerView(context).apply {
                    layoutManager = LinearLayoutManager(context)
                    adapter = CascadeAdapter(items) { item ->
                        onItemSelected(level, item)
                    }
                }
                
                // 添加分隔线（除了第一级）
                if (level > 0) {
                    val divider = View(context).apply {
                        layoutParams = LayoutParams(
                            dpToPx(context, 1f),
                            LayoutParams.MATCH_PARENT
                        )
                        setBackgroundColor(Color.parseColor("#E5E5EA"))
                    }
                    addView(divider)
                }
                
                addView(recyclerView, LayoutParams(
                    0,
                    LayoutParams.MATCH_PARENT,
                    1f
                ))
                
                recyclerViews.add(recyclerView)
                adapters.add(recyclerView.adapter as CascadeAdapter)
            }
        }
        
        /**
         * 处理项目选择
         */
        private fun onItemSelected(level: Int, item: CascadeData) {
            // 更新选中路径
            while (selectedPath.size > level) {
                selectedPath.removeAt(selectedPath.size - 1)
            }
            selectedPath.add(item.label)
            
            // 如果有子级，显示下一级
            if (!item.children.isNullOrEmpty()) {
                setupLevel(level + 1, item.children)
            } else {
                // 没有子级，移除后续级别
                while (recyclerViews.size > level + 1) {
                    removeView(recyclerViews.removeAt(recyclerViews.size - 1))
                    adapters.removeAt(adapters.size - 1)
                }
            }
        }
        
        /**
         * 获取选中的路径
         */
        fun getSelectedPath(): List<String> {
            return selectedPath.toList()
        }
    }
    
    /**
     * 级联适配器
     */
    private class CascadeAdapter(
        private var items: List<CascadeData>,
        private val onItemClick: (CascadeData) -> Unit
    ) : RecyclerView.Adapter<CascadeAdapter.ViewHolder>() {
        
        private var selectedPosition = -1
        
        fun updateData(newItems: List<CascadeData>) {
            items = newItems
            selectedPosition = -1
            notifyDataSetChanged()
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val textView = TextView(parent.context).apply {
                textSize = 16f
                setTextColor(Color.parseColor("#000000"))
                setPadding(dpToPx(parent.context, 16f), dpToPx(parent.context, 12f), dpToPx(parent.context, 16f), dpToPx(parent.context, 12f))
                gravity = Gravity.CENTER_VERTICAL
                setBackgroundResource(android.R.drawable.list_selector_background)
            }
            return ViewHolder(textView)
        }
        
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = items[position]
            holder.textView.text = item.label
            
            // 选中状态
            if (position == selectedPosition) {
                holder.textView.setTextColor(Color.parseColor("#007AFF"))
                holder.textView.setTypeface(null, android.graphics.Typeface.BOLD)
            } else {
                holder.textView.setTextColor(Color.parseColor("#000000"))
                holder.textView.setTypeface(null, android.graphics.Typeface.NORMAL)
            }
            
            holder.textView.setOnClickListener {
                val oldPosition = selectedPosition
                selectedPosition = position
                if (oldPosition >= 0) {
                    notifyItemChanged(oldPosition)
                }
                notifyItemChanged(position)
                onItemClick(item)
            }
        }
        
        override fun getItemCount() = items.size
        
        class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
    }
    
    /**
     * dp 转 px
     */
    private fun dpToPx(context: Context, dp: Float): Int {
        val density = context.resources.displayMetrics.density
        return (dp * density + 0.5f).toInt()
    }
    
    /**
     * dp 转 px（重载方法，兼容 Int 参数）
     */
    private fun dpToPx(context: Context, dp: Int): Int {
        return dpToPx(context, dp.toFloat())
    }
}

