package kr.co.vividnext.sodalive.audio_content.comment

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.DialogAudioContentCommentBinding

class AudioContentCommentFragment(
    private val creatorId: Long,
    private val audioContentId: Long,
    private val isShowSecret: Boolean
) : BottomSheetDialogFragment() {

    private lateinit var binding: DialogAudioContentCommentBinding

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)

        dialog.setOnShowListener {
            val d = it as BottomSheetDialog
            val bottomSheet = d.findViewById<FrameLayout>(
                com.google.android.material.R.id.design_bottom_sheet
            )
            if (bottomSheet != null) {
                BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_EXPANDED
            }
        }

        return dialog
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val commentListFragmentTag = "COMMENT_LIST_FRAGMENT"
        val commentListFragment = AudioContentCommentListFragment.newInstance(
            creatorId = creatorId,
            audioContentId = audioContentId,
            isShowSecret = isShowSecret
        )
        val fragmentTransaction = childFragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.fl_container, commentListFragment, commentListFragmentTag)
        fragmentTransaction.addToBackStack(commentListFragmentTag)
        fragmentTransaction.commit()
    }

    fun hideCommentDialog() {
        dialog?.dismiss()
    }

    fun onClickComment(comment: GetAudioContentCommentListItem) {
        val commentReplyFragmentTag = "COMMENT_REPLY_FRAGMENT"
        val commentReplyFragment = AudioContentCommentReplyFragment.newInstance(
            creatorId = creatorId,
            audioContentId = audioContentId,
            comment = comment
        )
        val fragmentTransaction = childFragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.fl_container, commentReplyFragment, commentReplyFragmentTag)
        fragmentTransaction.addToBackStack(commentReplyFragmentTag)
        fragmentTransaction.commit()
    }
}
