package com.adealink.weparty.im.session.comp.fragment.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.util.onClick
import com.adealink.weparty.R
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.im.databinding.ViewSessionOrderTopBarBinding
import com.adealink.weparty.im.session.comp.fragment.listener.IGoVoiceCallback
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.adealink.weparty.module.order.data.OrderStatus
import okhttp3.internal.format
import kotlin.math.max

class UserOrderTopBarView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0,
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val binding =
        ViewSessionOrderTopBarBinding.inflate(LayoutInflater.from(context), this)

    private var data: OrderDetailInfo? = null

    private var countDownSecond: Long = 0

    private var goVoiceCallback: IGoVoiceCallback? = null

    fun setGoVoiceCallback(callback: IGoVoiceCallback?) {
        this.goVoiceCallback = callback
    }

    private val countDownRunnable = Runnable {
        if (isAttachedToWindow) {
            updateCountDownText()
            countDownSecond = max(0, countDownSecond - 1)
            startReplyCountDown(1000)
        }
    }

    init {
        binding.btnGoVoice.onClick {
            goVoiceCallback?.goVoice()
        }
    }

    @SuppressLint("SetTextI18n")
    fun setOrder(data: OrderDetailInfo) {
        this.data = data
        binding.ivOrderCategory.setImageUrl(data.categoryIcon)
        val orderStatus = OrderStatus.map(data.status)
        binding.tvOrderCategory.text = getUserOrderStatusText(orderStatus, data.refundApply)
        binding.tvOrderCategoryDesc.text = "${data.categoryName}/${data.unit} x${data.purchaseQty}"

        if (data.isPendingAccept()) {
            val endTs = data.createTime + 3_600_000
            this.countDownSecond = max(endTs - System.currentTimeMillis(), 0) / 1000
            startReplyCountDown(0)
        } else {
            this.countDownSecond = 0
            stopReplyCountDown()
        }
        binding.btnGoVoice.show(data.isInService())
    }

    fun getUserOrderStatusText(
        status: OrderStatus?,
        isRefundApply: Boolean? //是否处于申请退款中
    ): String? {
        if (isRefundApply == true) {
            return getCompatString(R.string.user_order_status_refund_under_review_desc)
        }
        return when (status) {
            OrderStatus.CREATE_ORDER -> {
                getCompatString(R.string.user_order_status_create_order_desc)
            }

            OrderStatus.WAIT_FOR_ACCEPT -> {
                getCompatString(R.string.user_order_status_wait_accept_desc)
            }

            OrderStatus.PLAYMATE_ACCEPT -> {
                getCompatString(R.string.user_order_status_accept_desc)
            }

            OrderStatus.PLAYMATE_IN_SERVICE -> {
                getCompatString(R.string.user_order_status_in_service_desc)
            }

            OrderStatus.PLAYMATE_END_SERVICE -> {
                getCompatString(R.string.user_order_status_end_service_desc)
            }

            OrderStatus.PLAYMATE_REFUSE -> {
                getCompatString(R.string.user_order_status_playmate_refuse_desc)
            }

            OrderStatus.COMPLETE -> {
                getCompatString(R.string.user_order_status_complete_desc)
            }

            OrderStatus.USER_REFUND -> {
                getCompatString(R.string.user_order_status_user_refund_desc)
            }

            OrderStatus.USER_CANCEL -> {
                getCompatString(R.string.user_order_status_user_cancel_desc)
            }

            null -> {
                null
            }
        }
    }

    private fun startReplyCountDown(delay: Long = 1000) {
        if (data?.isPendingAccept() == false) {
            binding.clCountDown.gone()
            return
        }
        binding.clCountDown.show()
        updateCountDownText()
        if (countDownSecond >= 0) {
            removeCallbacks(countDownRunnable)
            postDelayed(countDownRunnable, delay)
        }
    }

    private fun stopReplyCountDown() {
        binding.clCountDown.gone()
        removeCallbacks(countDownRunnable)
    }

    @SuppressLint("SetTextI18n")
    private fun updateCountDownText() {
        val minute = countDownSecond / 60
        val second = countDownSecond % 60
        binding.tvRelayCountdown.text = "${format("%02d", minute)}:${format("%02d", second)}"
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startReplyCountDown(0)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopReplyCountDown()
    }
}