package kr.co.vividnext.sodalive.explorer.profile.creator_community.all.comment

import android.annotation.SuppressLint
import android.app.Service
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.os.BundleCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.CircleCropTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.base.SodaDialog
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.FragmentAudioContentCommentReplyBinding
import kr.co.vividnext.sodalive.dialog.MemberProfileDialog
import kr.co.vividnext.sodalive.explorer.profile.creator_community.GetCommunityPostCommentListItem
import kr.co.vividnext.sodalive.extensions.dpToPx
import org.koin.android.ext.android.inject

class CreatorCommunityCommentReplyFragment : BaseFragment<FragmentAudioContentCommentReplyBinding>(
    FragmentAudioContentCommentReplyBinding::inflate
) {
    private val viewModel: CreatorCommunityCommentListViewModel by inject()

    private lateinit var imm: InputMethodManager
    private lateinit var loadingDialog: LoadingDialog
    private lateinit var adapter: CreatorCommunityCommentReplyAdapter

    private var originalComment: GetCommunityPostCommentListItem? = null
    private var creatorId: Long = 0
    private var postId: Long = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        creatorId = arguments?.getLong(Constants.EXTRA_COMMUNITY_CREATOR_ID) ?: 0
        postId = arguments?.getLong(Constants.EXTRA_COMMUNITY_POST_ID) ?: 0
        originalComment = BundleCompat.getParcelable(
            requireArguments(),
            Constants.EXTRA_COMMUNITY_POST_COMMENT,
            GetCommunityPostCommentListItem::class.java
        )
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (originalComment == null) {
            parentFragmentManager.popBackStack()
        }

        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)
        imm = requireContext().getSystemService(
            Service.INPUT_METHOD_SERVICE
        ) as InputMethodManager

        setupView()
        bindData()
        viewModel.getCommentReplyList(commentId = originalComment!!.id) {
            parentFragmentManager.popBackStack()
        }
    }

    private fun hideDialog() {
        (parentFragment as CreatorCommunityCommentFragment).hideCommentDialog()
    }

    private fun setupView() {
        binding.root.setOnClickListener { }

        binding.tvBack.setOnClickListener {
            parentFragmentManager.popBackStack()
        }

        binding.ivClose.setOnClickListener { hideDialog() }

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

        binding.ivCommentSend.setOnClickListener {
            hideKeyboard()
            val comment = binding.etComment.text.toString()
            binding.etComment.setText("")
            viewModel.registerComment(postId, comment, originalComment!!.id)
        }

        adapter = CreatorCommunityCommentReplyAdapter(
            creatorId = creatorId,
            modifyComment = { commentId, comment ->
                hideKeyboard()
                viewModel.modifyComment(
                    commentId = commentId,
                    postId = postId,
                    parentCommentId = originalComment!!.id,
                    comment = comment
                )
            },
            onClickDelete = {
                SodaDialog(
                    activity = requireActivity(),
                    layoutInflater = layoutInflater,
                    title = "댓글 삭제",
                    desc = "삭제하시겠습니까?",
                    confirmButtonTitle = "삭제",
                    confirmButtonClick = {
                        viewModel.modifyComment(
                            commentId = it,
                            postId = postId,
                            parentCommentId = originalComment!!.id,
                            isActive = false
                        )
                    },
                    cancelButtonTitle = "취소",
                    cancelButtonClick = {}
                ).show(screenWidth)
            },
            onClickProfile = {
                MemberProfileDialog(
                    activity = requireActivity(),
                    layoutInflater = layoutInflater,
                    memberId = it,
                    screenWidth = screenWidth
                ).show()
            }
        ).apply {
            items.add(originalComment!!)
        }

        val recyclerView = binding.rvCommentReply
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(
            activity,
            LinearLayoutManager.VERTICAL,
            false
        )

        recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)

                outRect.left = 13.3f.dpToPx().toInt()
                outRect.right = 13.3f.dpToPx().toInt()

                when (parent.getChildAdapterPosition(view)) {
                    0 -> {
                        outRect.top = 13.3f.dpToPx().toInt()
                        outRect.bottom = 12f.dpToPx().toInt()
                    }

                    adapter.itemCount - 1 -> {
                        outRect.top = 12f.dpToPx().toInt()
                        outRect.bottom = 13.3f.dpToPx().toInt()
                    }

                    else -> {
                        outRect.top = 12f.dpToPx().toInt()
                        outRect.bottom = 12f.dpToPx().toInt()
                    }
                }
            }
        })

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val lastVisibleItemPosition = (recyclerView.layoutManager as LinearLayoutManager?)!!
                    .findLastCompletelyVisibleItemPosition()
                val itemTotalCount = recyclerView.adapter!!.itemCount - 1

                // 스크롤이 끝에 도달했는지 확인
                if (!recyclerView.canScrollVertically(1) &&
                    lastVisibleItemPosition == itemTotalCount
                ) {
                    viewModel.getCommentReplyList(originalComment!!.id)
                }
            }
        })

        recyclerView.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun bindData() {
        viewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

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

        viewModel.commentList.observe(viewLifecycleOwner) {
            if (viewModel.page - 1 == 1) {
                adapter.items.clear()
                binding.rvCommentReply.scrollToPosition(0)
                adapter.items.add(originalComment!!)
            }

            adapter.items.addAll(it)
            adapter.notifyDataSetChanged()
        }
    }

    private fun hideKeyboard() {
        imm.hideSoftInputFromWindow(view?.windowToken, 0)
    }

    companion object {
        fun newInstance(
            creatorId: Long,
            postId: Long,
            comment: GetCommunityPostCommentListItem
        ): CreatorCommunityCommentReplyFragment {
            val args = Bundle()
            args.putLong(Constants.EXTRA_COMMUNITY_POST_ID, postId)
            args.putLong(Constants.EXTRA_COMMUNITY_CREATOR_ID, creatorId)
            args.putParcelable(Constants.EXTRA_COMMUNITY_POST_COMMENT, comment)

            val fragment = CreatorCommunityCommentReplyFragment()
            fragment.arguments = args
            return fragment
        }
    }
}
