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

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import coil.load
import coil.transform.RoundedCornersTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.DialogLiveRoomInfoUpdateBinding
import kr.co.vividnext.sodalive.extensions.dpToPx

class LiveRoomInfoEditDialog(
    activity: Activity,
    layoutInflater: LayoutInflater,
    onClickImagePicker: () -> Unit
) {
    private val alertDialog: AlertDialog
    private val dialogView = DialogLiveRoomInfoUpdateBinding.inflate(layoutInflater)

    private var coverImageUrl: String? = null
    private var coverImageUri: Uri? = null

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

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

        dialogView.ivPhotoPicker.setOnClickListener { onClickImagePicker() }
        dialogView.ivClose.setOnClickListener { alertDialog.dismiss() }
        dialogView.tvCancel.setOnClickListener { alertDialog.dismiss() }
    }

    fun setRoomInfo(
        currentTitle: String,
        currentContent: String,
    ) {
        dialogView.etTitle.setText(currentTitle)
        dialogView.etContent.setText(currentContent)
    }

    fun setCoverImageUri(coverImageUri: Uri) {
        this.coverImageUri = coverImageUri
        dialogView.ivCover.load(coverImageUri) {
            crossfade(true)
            placeholder(R.drawable.ic_logo)
            transformations(RoundedCornersTransformation(13.3f.dpToPx()))
        }
    }

    fun setCoverImageUrl(coverImageUrl: String) {
        this.coverImageUrl = coverImageUrl
        dialogView.ivCover.load(coverImageUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_logo)
            transformations(RoundedCornersTransformation(13.3f.dpToPx()))
        }
    }

    fun setConfirmAction(confirmAction: (String, String, Uri?) -> Unit) {
        dialogView.tvConfirm.setOnClickListener {
            alertDialog.dismiss()

            val newTitle = dialogView.etTitle.text.toString()
            val newContent = dialogView.etContent.text.toString()
            confirmAction(newTitle, newContent, coverImageUri)
            coverImageUri = null
            coverImageUrl = null
        }
    }

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