package kr.co.vividnext.sodalive.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import coil.load
import coil.transform.RoundedCornersTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.DialogMemberProfileBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.report.ProfileReportDialog
import kr.co.vividnext.sodalive.report.ReportType
import kr.co.vividnext.sodalive.report.UserReportDialog
import kr.co.vividnext.sodalive.settings.notification.MemberRole
import kr.co.vividnext.sodalive.user.UserViewModel
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class MemberProfileDialog(
    private val activity: FragmentActivity,
    private val layoutInflater: LayoutInflater,
    private val memberId: Long,
    private val screenWidth: Int
) : KoinComponent {

    private val viewModel: UserViewModel by inject()
    private val alertDialog: AlertDialog

    val dialogView = DialogMemberProfileBinding.inflate(layoutInflater)

    private lateinit var loadingDialog: LoadingDialog

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

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

        setupView()
        bindData()
    }

    fun dismiss() {
        alertDialog.dismiss()
    }

    fun show() {
        viewModel.getMemberProfile(memberId) {
            alertDialog.show()

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

            alertDialog.window?.attributes = lp
        }
    }

    private fun setupView() {
        loadingDialog = LoadingDialog(activity, layoutInflater)

        val profileLP = dialogView.ivProfile.layoutParams
        profileLP.width = activity.resources.displayMetrics.widthPixels - (66.7f.dpToPx()).toInt()
        profileLP.height = activity.resources.displayMetrics.widthPixels - (66.7f.dpToPx()).toInt()
        dialogView.ivProfile.layoutParams = profileLP
        dialogView.ivClose.setOnClickListener { dismiss() }
    }

    private fun bindData() {
        viewModel.isLoading.observe(activity) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.toastLiveData.observe(activity) {
            Toast.makeText(activity, it, Toast.LENGTH_SHORT).show()
        }

        viewModel.memberProfile.observe(activity) {
            dialogView.ivProfile.load(it.profileImageUrl) {
                crossfade(true)
                placeholder(R.drawable.ic_place_holder)
                transformations(RoundedCornersTransformation(8.dpToPx()))
            }

            dialogView.tvNickname.text = it.nickname
            dialogView.tvBlockMember.text = if (it.isBlocked) {
                "차단 해제"
            } else {
                "차단"
            }

            dialogView.tvBlockMember.setOnClickListener { _ ->
                if (it.isBlocked) {
                    viewModel.memberUnBlock(it.memberId) { dismiss() }
                } else {
                    showMemberBlockDialog(it.memberId, it.nickname)
                }
            }

            dialogView.tvReportMember.setOnClickListener { _ ->
                showMemberReportDialog(it.memberId)
            }

            dialogView.tvReportMemberProfile.setOnClickListener { _ ->
                showProfileReportDialog(it.memberId)
            }
        }
    }

    private fun showMemberBlockDialog(memberId: Long, nickname: String) {
        val message = if (SharedPreferenceManager.role == MemberRole.CREATOR.name) {
            """
                ${nickname}님을 차단하시겠습니까?

                사용자를 차단하면 사용자는 아래 기능이 제한됩니다.
                - 내가 개설한 라이브 입장 불가
                - 나에게 메시지 보내기 불가
                - 내 채널의 팬Talk 작성불가
            """.trimIndent()
        } else {
            """
                ${nickname}님을 차단하시겠습니까?

                - 사용자를 차단하면 '차단한 사용자의 라이브 중 채팅'이 보이지 않습니다.
            """.trimIndent()
        }
        val dialog = android.app.AlertDialog.Builder(activity)
        dialog.setTitle("사용자 차단")
        dialog.setMessage(message)
        dialog.setPositiveButton("차단") { _, _ ->
            viewModel.memberBlock(memberId) { dismiss() }
        }
        dialog.setNegativeButton("취소") { _, _ -> }
        dialog.show()
    }

    private fun showMemberReportDialog(memberId: Long) {
        val dialog = UserReportDialog(activity, layoutInflater) {
            viewModel.report(
                type = ReportType.USER,
                userId = memberId,
                reason = it
            ) { dismiss() }
        }

        dialog.show(screenWidth)
    }

    private fun showProfileReportDialog(memberId: Long) {
        val dialog = ProfileReportDialog(activity, layoutInflater) {
            viewModel.report(
                type = ReportType.PROFILE,
                userId = memberId
            ) { dismiss() }
        }

        dialog.show(screenWidth)
    }
}
