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 android.widget.Toast
import androidx.appcompat.app.AlertDialog
import kr.co.vividnext.sodalive.databinding.DialogLiveInputBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class LiveCancelDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    title: String,
    hint: String,
    confirmButtonTitle: String,
    confirmButtonClick: (String) -> Unit,
    cancelButtonTitle: String = "",
    cancelButtonClick: (() -> Unit)? = null,
) {
    private val alertDialog: AlertDialog
    private val dialogView = DialogLiveInputBinding.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.etReason.hint = hint

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

        dialogView.tvConfirm.text = confirmButtonTitle
        dialogView.tvConfirm.setOnClickListener {
            if (dialogView.etReason.text.isNotBlank()) {
                alertDialog.dismiss()
                confirmButtonClick(dialogView.etReason.text.toString())
            } else {
                Toast.makeText(activity, "취소사유를 입력하세요.", Toast.LENGTH_LONG).show()
            }
        }

        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) {
        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
    }
}
