package com.lukouguoji.aerologic.page.log.detail

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.aerologic.R

class LogDetailStepAdapter : RecyclerView.Adapter<LogDetailStepAdapter.StepViewHolder>() {

    private var steps: List<String> = emptyList()
    private var currentIndex: Int = -1

    fun setData(steps: List<String>, currentIndex: Int) {
        this.steps = steps
        this.currentIndex = currentIndex
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StepViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_log_step, parent, false)
        return StepViewHolder(view)
    }

    override fun onBindViewHolder(holder: StepViewHolder, position: Int) {
        val step = steps[position]
        val isCompleted = position <= currentIndex
        val isCurrent = position == currentIndex
        val isFirst = position == 0
        val isLast = position == steps.size - 1

        // 步骤名称
        if (isCurrent) {
            holder.tvStepName.setBackgroundResource(R.drawable.bg_step_current_badge)
            holder.tvStepName.setTextColor(0xFFFFFFFF.toInt())
        } else {
            holder.tvStepName.setBackgroundResource(0)
            holder.tvStepName.setTextColor(
                if (isCompleted) 0xFF333333.toInt() else 0xFF999999.toInt()
            )
        }
        holder.tvStepName.text = step

        // 圆点
        holder.dotView.setBackgroundResource(
            when {
                isCurrent -> R.drawable.bg_step_dot_green
                isCompleted -> R.drawable.bg_step_dot_blue
                else -> R.drawable.bg_step_dot_gray
            }
        )

        // 左侧连线
        holder.lineLeft.visibility = if (isFirst) View.INVISIBLE else View.VISIBLE
        holder.lineLeft.setBackgroundColor(
            if (isCompleted) 0xFF1C8CF5.toInt() else 0xFFCCCCCC.toInt()
        )

        // 右侧连线
        holder.lineRight.visibility = if (isLast) View.INVISIBLE else View.VISIBLE
        holder.lineRight.setBackgroundColor(
            if (isCompleted && position < currentIndex) 0xFF1C8CF5.toInt() else 0xFFCCCCCC.toInt()
        )
    }

    override fun getItemCount(): Int = steps.size

    class StepViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvStepName: TextView = view.findViewById(R.id.tv_step_name)
        val dotView: View = view.findViewById(R.id.view_dot)
        val lineLeft: View = view.findViewById(R.id.view_line_left)
        val lineRight: View = view.findViewById(R.id.view_line_right)
    }
}
