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

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import coil.load
import coil.transform.CircleCropTransformation
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.DialogLiveRoomDonationBinding
import kr.co.vividnext.sodalive.extensions.moneyFormat
import kr.co.vividnext.sodalive.extensions.prefix
import kr.co.vividnext.sodalive.mypage.can.charge.CanChargeActivity

class LiveRoomDonationDialog(
    private val activity: AppCompatActivity,
    layoutInflater: LayoutInflater,
    isLiveDonation: Boolean = false,
    onClickDonation: (Int, String, Boolean) -> Unit
) {

    private val bottomSheetDialog: BottomSheetDialog = BottomSheetDialog(activity)
    private val dialogView = DialogLiveRoomDonationBinding.inflate(layoutInflater)

    init {
        bottomSheetDialog.setContentView(dialogView.root)
        bottomSheetDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        bottomSheetDialog.setCancelable(false)

        val bottomSheetInternal = bottomSheetDialog.findViewById<FrameLayout>(
            com.google.android.material.R.id.design_bottom_sheet
        )

        if (bottomSheetInternal != null) {
            val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal)
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
            bottomSheetBehavior.skipCollapsed = true
        }

        dialogView.tvCancel.setOnClickListener { bottomSheetDialog.dismiss() }
        dialogView.tvDonation.setOnClickListener {
            try {
                val can = dialogView.etDonationCan.text.toString().toInt()
                val message = dialogView.etDonationMessage.text.toString().prefix(200)

                if (isLiveDonation) {
                    val isSecret = dialogView.tvSecret.isSelected

                    if (isSecret && can < 10) {
                        Toast.makeText(
                            activity,
                            "비밀 미션은 최소 10캔 이상부터 이용이 가능합니다.",
                            Toast.LENGTH_LONG
                        ).show()
                    } else if (can < 1) {
                        Toast.makeText(
                            activity,
                            "1캔 이상 후원하실 수 있습니다.",
                            Toast.LENGTH_LONG
                        ).show()
                    } else {
                        bottomSheetDialog.dismiss()
                        onClickDonation(can, message, isSecret)
                    }
                } else {
                    if (can > 0) {
                        bottomSheetDialog.dismiss()
                        onClickDonation(can, message, dialogView.tvSecret.isSelected)
                    } else {
                        Toast.makeText(
                            activity,
                            "1캔 이상 후원하실 수 있습니다.",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }
            } catch (e: NumberFormatException) {
                Toast.makeText(
                    activity,
                    "1캔 이상 후원하실 수 있습니다.",
                    Toast.LENGTH_LONG
                ).show()
            }
        }

        if (isLiveDonation) {
            dialogView.rlSecret.visibility = View.VISIBLE
            dialogView.tvSecret.setOnClickListener {
                val isSelected = dialogView.tvSecret.isSelected
                dialogView.tvSecret.isSelected = !isSelected
                dialogView.etDonationMessage.hint = if (!isSelected) {
                    "비밀 미션을 입력하세요(최대 200자)"
                } else {
                    "함께 보낼 메시지 입력(최대 200자)"
                }
                dialogView.etDonationCan.hint = if (!isSelected) {
                    "10캔 이상 입력하세요"
                } else {
                    "1캔 이상 입력하세요"
                }
            }
            dialogView.tvSecret.isSelected = false
        } else {
            dialogView.rlSecret.visibility = View.GONE
        }

        setupView()
    }

    fun show(width: Int) {
        if (!bottomSheetDialog.isShowing) {
            bottomSheetDialog.show()

            val lp = WindowManager.LayoutParams()
            lp.copyFrom(bottomSheetDialog.window?.attributes)
            lp.width = width
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT

            bottomSheetDialog.window?.attributes = lp

            dialogView.scrollView.post {
                dialogView.scrollView.fullScroll(View.FOCUS_DOWN)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setupView() {
        dialogView.tvCan.text = SharedPreferenceManager.can.moneyFormat()
        dialogView.tvPlus10.setOnClickListener { addCan(10) }
        dialogView.tvPlus100.setOnClickListener { addCan(100) }
        dialogView.tvPlus1000.setOnClickListener { addCan(1000) }
        dialogView.tvPlus10000.setOnClickListener { addCan(10000) }

        dialogView.ivProfile.load(SharedPreferenceManager.profileImage) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(CircleCropTransformation())
        }

        dialogView.tvCan.setOnClickListener {
            bottomSheetDialog.dismiss()

            val intent = Intent(activity, CanChargeActivity::class.java)
            intent.putExtra(Constants.EXTRA_GO_TO_PREV_PAGE, true)
            activity.startActivity(intent)
        }

        dialogView.tvCharge.setOnClickListener {
            bottomSheetDialog.dismiss()

            val intent = Intent(activity, CanChargeActivity::class.java)
            intent.putExtra(Constants.EXTRA_GO_TO_PREV_PAGE, true)
            activity.startActivity(intent)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun addCan(can: Int) {
        try {
            val currentCan = dialogView.etDonationCan.text.toString().toInt()
            dialogView.etDonationCan.setText((currentCan + can).toString())
        } catch (e: NumberFormatException) {
            dialogView.etDonationCan.setText(can.toString())
        }
    }
}
