package kr.co.vividnext.sodalive.live.room.dialog

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import kr.co.vividnext.sodalive.databinding.DialogLivePaymentBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class LivePaymentDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    title: String,
    desc: String,
    desc2: String? = null,
    startDateTime: String? = null,
    nowDateTime: String? = null,
    confirmButtonTitle: String,
    confirmButtonClick: () -> Unit,
    cancelButtonTitle: String = "",
    cancelButtonClick: (() -> Unit)? = null,
) {
    private val alertDialog: AlertDialog
    private val dialogView = DialogLivePaymentBinding.inflate(layoutInflater)

    init {
        val dialogBuilder = AlertDialog.Builder(activity)
        dialogBuilder.setView(dialogView.root)

        alertDialog = dialogBuilder.create()
        alertDialog.setCancelable(false)
        alertDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        dialogView.tvTitle.text = title
        dialogView.tvDesc.text = desc

        if (startDateTime != null && nowDateTime != null) {
            dialogView.tvDesc2.text = desc2
            dialogView.tvNowDate.text = nowDateTime
            dialogView.tvStartDate.text = startDateTime

            dialogView.tvDesc2.visibility = View.VISIBLE
            dialogView.llTimeNotice.visibility = View.VISIBLE
        } else {
            dialogView.tvDesc2.visibility = View.GONE
            dialogView.llTimeNotice.visibility = View.GONE
        }

        dialogView.tvCancel.text = cancelButtonTitle
        dialogView.tvCancel.setOnClickListener {
            alertDialog.dismiss()
            cancelButtonClick?.let { it() }
        }

        dialogView.tvConfirm.text = confirmButtonTitle
        dialogView.tvConfirm.setOnClickListener {
            alertDialog.dismiss()
            confirmButtonClick()
        }

        dialogView.tvCancel.visibility = if (cancelButtonTitle.isNotBlank()) {
            View.VISIBLE
        } else {
            View.GONE
        }

        dialogView.tvConfirm.visibility = if (confirmButtonTitle.isNotBlank()) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    fun show(width: Int, message: String = "") {
        alertDialog.show()

        val lp = WindowManager.LayoutParams()
        lp.copyFrom(alertDialog.window?.attributes)
        lp.width = width - (26.7f.dpToPx()).toInt()
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT

        alertDialog.window?.attributes = lp
    }
}
