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

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.URLUtil
import android.widget.FrameLayout
import android.widget.Toast
import coil.load
import coil.transform.CircleCropTransformation
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.FragmentLiveRoomDetailBinding
import kr.co.vividnext.sodalive.explorer.profile.UserProfileActivity
import org.koin.android.ext.android.inject

class LiveRoomDetailFragment(
    private val roomId: Long,
    private val onClickParticipant: () -> Unit,
    private val onClickReservation: () -> Unit,
    private val onClickModify: (GetRoomDetailResponse) -> Unit,
    private val onClickStart: () -> Unit,
    private val onClickCancel: () -> Unit
) : BottomSheetDialogFragment() {

    private val viewModel: LiveRoomDetailViewModel by inject()

    private lateinit var binding: FragmentLiveRoomDetailBinding

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var roomDetail: GetRoomDetailResponse

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentLiveRoomDetailBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)

        val bottomSheet = dialog?.findViewById<FrameLayout>(
            com.google.android.material.R.id.design_bottom_sheet
        )
        val behavior = BottomSheetBehavior.from<View>(bottomSheet!!)
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        bindData()
        viewModel.getDetail(roomId) { dismiss() }

        binding.ivClose.setOnClickListener { dismiss() }
    }

    private fun bindData() {
        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(resources.displayMetrics.widthPixels)
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.toastLiveData.observe(viewLifecycleOwner) {
            it?.let { Toast.makeText(requireActivity(), it, Toast.LENGTH_LONG).show() }
        }

        viewModel.liveRoomDetailLiveData.observe(viewLifecycleOwner) {
            roomDetail = it
            setRoomDetail(it)
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun setRoomDetail(response: GetRoomDetailResponse) {
        binding.tv19.visibility = if (response.isAdult) {
            View.VISIBLE
        } else {
            View.GONE
        }

        binding.tvTitle.text = response.title
        binding.tvDate.text = response.beginDateTime

        if (response.price > 0) {
            binding.tvCan.text = response.price.toString()
            binding.tvCan.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.ic_can,
                0
            )
        } else {
            binding.tvCan.text = "무료"
            binding.tvCan.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                0,
                0
            )
        }

        setManagerProfile(manager = response.manager)

        binding.tvTags.text = response.tags.joinToString(" ") { "#$it" }
        binding.tvContent.text = response.notice

        binding.ivShare.setOnClickListener { shareRoom(response) }
        binding.ivShare2.setOnClickListener { shareRoom(response) }

        if (response.channelName.isNullOrBlank()) {
            when {
                response.manager.id == SharedPreferenceManager.userId -> {
                    binding.llStartDelete.visibility = View.VISIBLE
                    binding.tvReservationComplete.visibility = View.GONE
                    binding.tvParticipateNow.visibility = View.GONE
                    binding.tvReservation.visibility = View.GONE
                    binding.tvModify.setOnClickListener {
                        onClickModify(roomDetail)
                        dismiss()
                    }
                    binding.tvLiveStart.setOnClickListener {
                        onClickStart()
                        dismiss()
                    }
                    binding.tvLiveCancel.setOnClickListener {
                        onClickCancel()
                        dismiss()
                    }
                }

                response.isPaid -> {
                    binding.tvReservationComplete.visibility = View.VISIBLE
                    binding.tvParticipateNow.visibility = View.GONE
                    binding.tvReservation.visibility = View.GONE
                    binding.llStartDelete.visibility = View.GONE
                }

                else -> {
                    binding.tvReservationComplete.visibility = View.GONE
                    binding.tvParticipateNow.visibility = View.GONE
                    binding.tvReservation.visibility = View.VISIBLE
                    binding.tvReservation.setOnClickListener {
                        onClickReservation()
                        dismiss()
                    }
                    binding.llStartDelete.visibility = View.GONE
                }
            }
        } else {
            binding.tvReservationComplete.visibility = View.GONE
            binding.tvParticipateNow.visibility = View.VISIBLE
            binding.tvReservation.visibility = View.GONE
            binding.tvParticipateNow.setOnClickListener {
                onClickParticipant()
                dismiss()
            }
            binding.llStartDelete.visibility = View.GONE
        }
    }

    private fun setManagerProfile(manager: GetRoomDetailManager) {
        binding.tvManagerNickname.text = manager.nickname
        binding.tvManagerIntroduce.text = manager.introduce
        binding.ivManagerProfile.load(manager.profileImageUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(CircleCropTransformation())
        }

        if (
            manager.websiteUrl.isNullOrBlank() ||
            !URLUtil.isValidUrl(manager.websiteUrl)
        ) {
            binding.ivManagerWebsite.visibility = View.GONE
        } else {
            binding.ivManagerWebsite.visibility = View.VISIBLE
            binding.ivManagerWebsite.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(manager.websiteUrl)))
            }
        }

        if (
            manager.blogUrl.isNullOrBlank() ||
            !URLUtil.isValidUrl(manager.blogUrl)
        ) {
            binding.ivManagerBlog.visibility = View.GONE
        } else {
            binding.ivManagerBlog.visibility = View.VISIBLE
            binding.ivManagerBlog.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(manager.blogUrl)))
            }
        }

        if (
            manager.instagramUrl.isNullOrBlank() ||
            !URLUtil.isValidUrl(manager.instagramUrl)
        ) {
            binding.ivManagerInstagram.visibility = View.GONE
        } else {
            binding.ivManagerInstagram.visibility = View.VISIBLE
            binding.ivManagerInstagram.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(manager.instagramUrl)))
            }
        }

        if (
            manager.youtubeUrl.isNullOrBlank() ||
            !URLUtil.isValidUrl(manager.youtubeUrl)
        ) {
            binding.ivManagerYoutube.visibility = View.GONE
        } else {
            binding.ivManagerYoutube.visibility = View.VISIBLE
            binding.ivManagerYoutube.setOnClickListener {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(manager.youtubeUrl)))
            }
        }

        if (manager.isCreator) {
            binding.tvManagerProfile.visibility = View.VISIBLE
            binding.tvManagerProfile.setOnClickListener {
                val intent = Intent(requireActivity(), UserProfileActivity::class.java)
                intent.putExtra(Constants.EXTRA_USER_ID, manager.id)
                startActivity(intent)
            }
        } else {
            binding.tvManagerProfile.visibility = View.GONE
        }
    }

    private fun shareRoom(response: GetRoomDetailResponse) {
        viewModel.shareRoomLink(
            response.roomId,
            response.isPrivateRoom,
            response.password
        ) {
            val intent = Intent(Intent.ACTION_SEND)
            intent.type = "text/plain"
            intent.putExtra(Intent.EXTRA_TEXT, it)

            val shareIntent = Intent.createChooser(intent, "라이브 공유")
            startActivity(shareIntent)
        }
    }
}
