package com.unibuy.v2.utils

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import java.util.Timer
import java.util.TimerTask

/**
 * 與 Fragment 生命週期綁定的安全倒數計時器（自 Luzui v2 移植）。
 */
class SafeCountdownUtil(private val lifecycle: Lifecycle) : DefaultLifecycleObserver {
    private var timer: Timer? = null
    private var currentTime = 0
    private var listener: CountdownListener? = null
    private var lastCallTime: Long = 0

    fun getCurrentSeconds(): Int {
        return currentTime
    }

    init {
        lifecycle.addObserver(this)
    }

    interface CountdownListener {
        fun onTick(seconds: Int)
        fun onFinish()
    }

    fun setCountdownListener(listener: CountdownListener) {
        this.listener = listener
    }

    // 安全啟動/重置方法（帶防抖）
    fun startOrReset(seconds: Int) {
        synchronized(this) {
            val now = System.currentTimeMillis()
            if (now - lastCallTime < 200) {
                return
            }
            lastCallTime = now

            timer?.cancel()
            currentTime = seconds
            listener?.onTick(currentTime)

            timer = Timer().apply {
                schedule(object : TimerTask() {
                    override fun run() {
                        if (currentTime > 0) {
                            currentTime--
                            listener?.onTick(currentTime)
                        } else {
                            stop()
                            listener?.onFinish()
                        }
                    }
                }, 1000, 1000)
            }
        }
    }

    fun stop() {
        synchronized(this) {
            timer?.cancel()
            timer = null
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        stop()
        lifecycle.removeObserver(this)
        listener = null
    }
}
