package com.adealink.weparty.profile.dynamic.fragment.video

import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import androidx.media3.common.C
import androidx.media3.common.Player.REPEAT_MODE_ONE
import androidx.media3.common.util.UnstableApi
import com.adealink.frame.aab.util.getCompatDimensionPixelSize
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.util.formatTime
import com.adealink.frame.util.naviBarHeight
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.dialogfragment.CommonTextActionDialog
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.exoplayer.ExoPlayerHelper
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.setting.Setting
import com.adealink.weparty.profile.R
import com.adealink.weparty.profile.databinding.FragmentDynamicVideoBinding
import com.adealink.weparty.profile.dynamic.data.DynamicMediaData
import com.adealink.weparty.profile.dynamic.data.publishNewCommentLD
import com.adealink.weparty.profile.dynamic.fragment.dialog.DynamicCommentDialog
import com.adealink.weparty.profile.dynamic.fragment.dialog.DynamicTalkDialog
import com.adealink.weparty.profile.dynamic.viewmodel.DynamicViewModel
import com.adealink.weparty.util.TIME_FORMAT_DMY_HMS
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.formatNumberStr
import com.adealink.weparty.R as APP_R

class VideoDynamicFragment : BaseFragment(R.layout.fragment_dynamic_video) {

    companion object {
        const val TAG = "VideoDynamicFragment"
    }

    private val binding by viewBinding(FragmentDynamicVideoBinding::bind)
    private val dynamicViewModel by activityViewModels<DynamicViewModel>()

    private var exoPlayerHelper: ExoPlayerHelper? = null

    private var showCommentWhenFirstEnter = false
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        showCommentWhenFirstEnter =
            activity?.intent?.getBooleanExtra(Profile.Dynamic.EXTRA_DYNAMIC_SHOW_COMMENT, false)
                ?: false
    }

    override fun initViews() {
        super.initViews()
        activity.applyImmersive { top ->
            binding.topBar.root.setPadding(
                16.dp(), top, 16.dp(), 0
            )
            binding.topBar.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
                height =
                    top + getCompatDimensionPixelSize(APP_R.dimen.common_top_bar_height)
            }
        }
        binding.topBar.ivBack.onClick {
            activity?.finish()
        }
        binding.topBar.btnMore.onClick {
            clickMore()
        }
        binding.bottomBar.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = activity.naviBarHeight() + 16.dp()
        }
        binding.bottomBar.clTalk.onClick {
            clickTalk()
        }
        binding.bottomBar.clLike.onClick {
            clickLike()
        }
        binding.bottomBar.clComment.onClick {
            clickComment()
        }
        binding.vPlayer.onClick {
            clickPlay()
        }
    }

    @UnstableApi
    override fun observeViewModel() {
        super.observeViewModel()

        var firstCommit = true
        dynamicViewModel.dynamicDetailLD.observe(viewLifecycleOwner) {
            binding.topBar.ivAvatar.setImageUrl(it.avatar)
            binding.topBar.tvUserName.text = it.nickname

            binding.dynamicInfo.tvText.text = it.textContent
            binding.dynamicInfo.tvTime.text = formatTime(it.createdAt, TIME_FORMAT_DMY_HMS)

            if (it.liked) {
                binding.bottomBar.ivLike.setImageResource(R.drawable.profile_dynamic_liked_ic)
            } else {
                binding.bottomBar.ivLike.setImageResource(R.drawable.profile_dynamic_video_like_ic)
            }
            if (it.likeCount > 0) {
                binding.bottomBar.tvLike.text = formatNumberStr(it.likeCount)
            } else {
                binding.bottomBar.tvLike.text = getCompatString(R.string.profile_dynamic_like)
            }

            if (it.commentCount > 0) {
                binding.bottomBar.tvComment.text = formatNumberStr(it.commentCount)
            } else {
                binding.bottomBar.tvComment.text = getCompatString(R.string.profile_dynamic_comment)
            }

            playVideo(it.medias.firstOrNull())

            if (firstCommit) {
                firstCommit = false
                if (showCommentWhenFirstEnter) {
                    clickComment()
                }
            }
        }
        publishNewCommentLD.observeWithoutCache(viewLifecycleOwner) {
            if (dynamicViewModel.dynamicDetailLD.value?.id == it.dynamicId) {
                dynamicViewModel.reloadDynamic()
            }
        }
    }

    @UnstableApi

    private fun playVideo(video: DynamicMediaData?) {
        video ?: return
        if (exoPlayerHelper != null) {
            return
        }
        exoPlayerHelper = ExoPlayerHelper
            .Builder(binding.root.context) { player ->
                binding.vPlayer.player = player
            }
            .uri(video.url)
            .scaleMode(C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
            .repeatMode(REPEAT_MODE_ONE)
            .playWhenReady(true)
            .playListener(
                doOnReadyCallback = {
                    binding.bottomBar.vProgress.bindPlayer(binding.vPlayer.player)
                },
                onPlayingChangedCallback = { playing ->
                    binding.btnPlay.show(!playing)
                }
            )
            .onPauseWhenBuffering {
                //onIsPlayingChangedForBuffering(it)
            }
            .build()
            .also {
                it.observe(lifecycle)
            }
    }

    private fun clickReport() {
        val act = activity ?: return
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        val uid = detailData.uid
        Router.build(act, Setting.Report.PATH)
            .putExtra(Setting.Report.EXTRA_UID, uid)
            .start()
    }

    private fun clickMore() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        if (detailData.uid == ProfileModule.getMyUid()) {
            CommonTextActionDialog.Builder()
                .addItem(APP_R.id.id_common_op_delete, APP_R.string.common_delete)
                .showCancel(true)
                .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                    override fun onActionClick(viewId: Int) {
                        when (viewId) {
                            APP_R.id.id_common_op_delete -> {
                                deleteDynamic()
                            }
                        }
                    }
                }).build().show(childFragmentManager)
        } else {
            CommonTextActionDialog.Builder()
                .addItem(APP_R.id.id_common_op_report, APP_R.string.common_report)
                .showCancel(true)
                .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                    override fun onActionClick(viewId: Int) {
                        when (viewId) {
                            APP_R.id.id_common_op_report -> {
                                clickReport()
                            }
                        }
                    }
                }).build().show(childFragmentManager)
        }
    }

    private fun deleteDynamic() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        fun deleteDynamicInner(dynamicId: String) {
            showLoading()
            dynamicViewModel.delete(dynamicId).observe(viewLifecycleOwner) { rlt ->
                dismissLoading()
                showToast(rlt)
                when (rlt) {
                    is Rlt.Failed -> {
                        //Ntd.
                    }

                    is Rlt.Success<*> -> {
                        activity?.finish()
                    }
                }
            }
        }
        CommonDialog.Builder()
            .title(getCompatString(APP_R.string.common_confirm_delete))
            .setShowDefaultCancel(true)
            .positiveText(getCompatString(APP_R.string.commonui_confirm))
            .onPositive {
                deleteDynamicInner(detailData.id)
            }
            .show(childFragmentManager, "DeleteDynamic")
    }

    private fun clickTalk() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        DynamicTalkDialog().apply {
            setDynamicId(detailData.id)
        }.show(childFragmentManager)
    }

    private fun clickLike() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        dynamicViewModel.like(detailData.id).observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showToast(rlt)
                }

                is Rlt.Success -> {
                    //Ntd.
                }
            }
        }
    }

    private fun clickComment() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        DynamicCommentDialog().apply {
            setDynamicId(detailData.id)
        }.show(childFragmentManager)
    }

    private fun clickPlay() {
        val player = binding.vPlayer.player
        if (player == null) {
            return
        }
        if (player.isPlaying) {
            player.pause()
        } else {
            player.play()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.bottomBar.vProgress.release()
    }

}