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

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import coil.load
import coil.transform.RoundedCornersTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.DialogLiveRoomInfoUpdateBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.live.room.create.LiveRoomCreateViewModel
import kr.co.vividnext.sodalive.live.room.menu.GetMenuPresetResponse

@SuppressLint("ClickableViewAccessibility")
class LiveRoomInfoEditDialog(
    private val activity: AppCompatActivity,
    layoutInflater: LayoutInflater,
    onClickImagePicker: () -> Unit
) {
    private val alertDialog: AlertDialog
    private val dialogView = DialogLiveRoomInfoUpdateBinding.inflate(layoutInflater)

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

    private var menuId = 0L
    private val menuList = mutableListOf<GetMenuPresetResponse>()

    private val isAdultLiveData = MutableLiveData(false)
    private val isActivateMenuLiveData = MutableLiveData(false)
    private val selectedMenuLiveData = MutableLiveData<LiveRoomCreateViewModel.SelectedMenu>()

    private var menu: String = ""
    private var isAdult: Boolean = false
    private var isActivateMenu: Boolean? = null

    private lateinit var selectedMenu: LiveRoomCreateViewModel.SelectedMenu

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

        dialogView.etNotice.setOnTouchListener { view, motionEvent ->
            view.parent.parent.requestDisallowInterceptTouchEvent(true)
            if ((motionEvent.action and MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
                view.parent.parent.requestDisallowInterceptTouchEvent(false)
            }
            false
        }

        dialogView.etMenu.setOnTouchListener { view, motionEvent ->
            view.parent.parent.requestDisallowInterceptTouchEvent(true)
            if ((motionEvent.action and MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
                view.parent.parent.requestDisallowInterceptTouchEvent(false)
            }
            false
        }

        dialogView.ivSwitch.setOnClickListener {
            isActivateMenuLiveData.value = !isActivateMenuLiveData.value!!
            isActivateMenu = isActivateMenuLiveData.value!!

            if (selectedMenuLiveData.value == null) {
                selectMenuPreset(LiveRoomCreateViewModel.SelectedMenu.MENU_1)
            }
        }

        dialogView.llSelectMenu1.setOnClickListener {
            selectMenuPreset(LiveRoomCreateViewModel.SelectedMenu.MENU_1)
        }

        dialogView.llSelectMenu2.setOnClickListener {
            selectMenuPreset(LiveRoomCreateViewModel.SelectedMenu.MENU_2)
        }

        dialogView.llSelectMenu3.setOnClickListener {
            selectMenuPreset(LiveRoomCreateViewModel.SelectedMenu.MENU_3)
        }

        if (SharedPreferenceManager.isAuth) {
            dialogView.llAdult.visibility = View.VISIBLE
            dialogView.ivAdultSwitch.setOnClickListener {
                isAdultLiveData.value = !isAdultLiveData.value!!
            }
        } else {
            dialogView.llAdult.visibility = View.GONE
        }

        selectedMenuLiveData.observe(activity) {
            deselectAllMenuPreset()

            when (it) {
                LiveRoomCreateViewModel.SelectedMenu.MENU_2 -> selectMenuPresetButton(
                    dialogView.ivSelectMenu2,
                    dialogView.llSelectMenu2,
                    dialogView.tvSelectMenu2
                )

                LiveRoomCreateViewModel.SelectedMenu.MENU_3 -> selectMenuPresetButton(
                    dialogView.ivSelectMenu3,
                    dialogView.llSelectMenu3,
                    dialogView.tvSelectMenu3
                )

                else -> selectMenuPresetButton(
                    dialogView.ivSelectMenu1,
                    dialogView.llSelectMenu1,
                    dialogView.tvSelectMenu1
                )
            }
        }

        isActivateMenuLiveData.observe(activity) {
            if (it) {
                dialogView.llEditMenu.visibility = View.VISIBLE
                dialogView.ivSwitch.setImageResource(R.drawable.btn_toggle_on_big)
            } else {
                dialogView.llEditMenu.visibility = View.GONE
                dialogView.ivSwitch.setImageResource(R.drawable.btn_toggle_off_big)
            }
        }

        isAdultLiveData.observe(activity) {
            dialogView.ivAdultSwitch.setImageResource(
                if (it) {
                    R.drawable.btn_toggle_on_big
                } else {
                    R.drawable.btn_toggle_off_big
                }
            )
        }
    }

    fun setRoomInfo(
        currentTitle: String,
        currentContent: String,
        isAdult: Boolean
    ) {
        dialogView.etTitle.setText(currentTitle)
        dialogView.etNotice.setText(currentContent)

        this.isAdult = isAdult
        isAdultLiveData.value = isAdult
    }

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

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

    fun setMenuPreset(menuList: List<GetMenuPresetResponse>) {
        this.menuList.clear()
        this.isActivateMenu = null
        this.menuList.addAll(menuList)
        this.selectedMenuLiveData.value = null
        menuList.forEachIndexed { index, menuPreset ->
            if (menuPreset.isActive) {
                selectedMenu = when (index) {
                    1 -> LiveRoomCreateViewModel.SelectedMenu.MENU_2
                    2 -> LiveRoomCreateViewModel.SelectedMenu.MENU_3
                    else -> LiveRoomCreateViewModel.SelectedMenu.MENU_1
                }

                isActivateMenuLiveData.value = true
                selectMenuPreset(selectedMenu)
            }
        }
    }

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

            val newTitle = dialogView.etTitle.text.toString()
            val newContent = dialogView.etNotice.text.toString()
            val menu = dialogView.etMenu.text.toString()

            confirmAction(
                newTitle,
                newContent,
                coverImageUri,
                if (isActivateMenu != null) {
                    isActivateMenu
                } else if (
                    this.menu != menu ||
                    (
                        this::selectedMenu.isInitialized &&
                            this.selectedMenu != selectedMenuLiveData.value!!
                        )
                ) {
                    true
                } else {
                    isActivateMenu
                },
                menuId,
                menu,
                if (isAdult != isAdultLiveData.value!!) {
                    isAdultLiveData.value!!
                } else {
                    null
                }
            )
            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
    }

    private fun deselectAllMenuPreset() {
        dialogView.ivSelectMenu1.visibility = View.GONE
        dialogView.ivSelectMenu2.visibility = View.GONE
        dialogView.ivSelectMenu3.visibility = View.GONE

        dialogView.llSelectMenu1.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
        dialogView.tvSelectMenu1.setTextColor(
            ContextCompat.getColor(
                activity,
                R.color.color_3bb9f1
            )
        )

        if (menuList.size > 0) {
            dialogView.llSelectMenu2.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
            dialogView.tvSelectMenu2.setTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.color_3bb9f1
                )
            )
        } else {
            dialogView.llSelectMenu2.setBackgroundResource(R.drawable.bg_round_corner_6_7_777777)
            dialogView.tvSelectMenu2.setTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.color_555555
                )
            )
        }

        if (menuList.size > 1) {
            dialogView.llSelectMenu3.setBackgroundResource(R.drawable.bg_round_corner_6_7_13181b)
            dialogView.tvSelectMenu3.setTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.color_3bb9f1
                )
            )
        } else {
            dialogView.llSelectMenu3.setBackgroundResource(R.drawable.bg_round_corner_6_7_777777)
            dialogView.tvSelectMenu3.setTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.color_555555
                )
            )
        }
    }

    private fun selectMenuPresetButton(
        ivSelectMenuPreset: ImageView,
        llSelectMenuPreset: LinearLayout,
        tvSelectMenuPreset: TextView
    ) {
        ivSelectMenuPreset.visibility = View.VISIBLE
        llSelectMenuPreset.setBackgroundResource(R.drawable.bg_round_corner_6_7_3bb9f1)
        tvSelectMenuPreset.setTextColor(
            ContextCompat.getColor(
                activity,
                R.color.color_eeeeee
            )
        )
    }

    private fun selectMenuPreset(selectedMenuPreset: LiveRoomCreateViewModel.SelectedMenu) {
        if (
            menuList.isEmpty() &&
            (
                selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_2 ||
                    selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_3
                )
        ) {
            Toast.makeText(activity, "메뉴 1을 먼저 설정하세요", Toast.LENGTH_SHORT).show()
            return
        }

        if (menuList.size == 1 && selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_3) {
            Toast.makeText(activity, "메뉴 1과 메뉴 2를 먼저 설정하세요", Toast.LENGTH_SHORT).show()
            return
        }

        if (selectedMenuLiveData.value != selectedMenuPreset) {
            selectedMenuLiveData.value = selectedMenuPreset

            if (menuList.size > selectedMenuPreset.ordinal) {
                val menuPreset = menuList[selectedMenuPreset.ordinal]

                menu = menuPreset.menu
                menuId = menuPreset.id
                dialogView.etMenu.setText(menuPreset.menu)
            } else {
                menu = ""
                menuId = 0
                dialogView.etMenu.setText("")
            }
        }
    }
}
