package rallyedto.sunedto.tumouredto.majorityedto.loseedto

import android.app.Dialog
import android.content.Context
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import com.base.datarecovery.R
import com.base.datarecovery.databinding.UsedtoBinding

class Offspringedto(context: Context, block: (() -> Unit)? = null) :
    Dialog(context, R.style.groundsedto) {
    private var countdownText: TextView? = null

    init {
        val binding = UsedtoBinding.inflate(LayoutInflater.from(context))
        setContentView(binding.root)
        setCancelable(false)
        countdownText = binding.alcoholedto
    }

    fun setButtonClickListener(viewId: Int, listener: () -> Unit) {
        val button = findViewById<View>(viewId) as? TextView
        button?.setOnClickListener {
            listener.invoke()
        }
    }

    fun setCountdownText(viewId: Int) {
        countdownText = findViewById(viewId)
    }

    fun updateCountdownText(seconds: String) {
        countdownText?.text = seconds
    }

    fun start() {
        countdownTimer.start()
    }

    override fun dismiss() {
        super.dismiss()
        // 清理引用
        countdownText = null
    }

    private val countdownTimer = object : CountDownTimer(3000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            val seconds = (millisUntilFinished / 1000).toInt() + 1
            countdownText?.text = "(${seconds})"
            countdownText?.isVisible = true
        }

        override fun onFinish() {
            block?.invoke()
            countdownText?.isVisible = false
            dismiss()
        }
    }
}