package com.adealink.weparty.profile.dynamic

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.aab.util.getCompatDimension
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.dialogfragment.CommonTextActionDialog
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.mediapicker.imageselect.comp.TakeFromAlbumComp
import com.adealink.weparty.commonui.mediapicker.imageselect.model.MediaType
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.diffutil.BaseListDiffUtil
import com.adealink.weparty.commonui.recycleview.itemdecoration.HorizontalItemDecoration
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.constant.PUBLISH_DYNAMIC_MAX_LENGTH
import com.adealink.weparty.module.image.data.PhotoData
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.profile.databinding.ActivityPublishDynamicBinding
import com.adealink.weparty.profile.dynamic.adapter.AddPhotoItemViewBinder
import com.adealink.weparty.profile.dynamic.adapter.PhotoItemViewBinder
import com.adealink.weparty.profile.dynamic.comp.PublishDynamicVideoComp
import com.adealink.weparty.profile.dynamic.viewmodel.PublishDynamicViewModel
import com.adealink.weparty.profile.edit.comp.PhotoWallItemTouchHelperCallback
import com.adealink.weparty.profile.edit.data.BaseMediaItemData
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.goImagePreviewActivity
import com.adealink.weparty.R as APP_R

@RouterUri(
    path = [
        Profile.PublishDynamic.PATH
    ],
    desc = "发布动态"
)
class PublishDynamicActivity : BaseActivity() {

    private val binding by viewBinding(ActivityPublishDynamicBinding::inflate)

    private val publishViewModel by viewModels<PublishDynamicViewModel> { ProfileViewModelFactory() }

    private val photoAdapter by fastLazy { MultiTypeListAdapter<BaseMediaItemData>(BaseListDiffUtil()) }

    private lateinit var photoTouchHelper: ItemTouchHelper
    private lateinit var photoTouchCallback: PhotoWallItemTouchHelperCallback
    private lateinit var takePhotoAlbumComp: TakeFromAlbumComp
    private lateinit var takeVideoAlbumComp: TakeFromAlbumComp

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
        applyImmersive { top ->
            binding.topBar.setPadding(0, top, 0, 0)
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                height = top + getCompatDimension(APP_R.dimen.common_top_bar_height).toInt()
            }
        }

        binding.ivBack.onClick {
            finish()
        }

        binding.btnPublish.isEnabled = false
        binding.btnPublish.onClick {
            publishDynamic()
        }

        photoAdapter.register(
            AddPhotoItemViewBinder {
                showMediaSelectAction()
            }
        )
        photoAdapter.register(
            PhotoItemViewBinder(
                this,
                onItemClick = {
                    previewPicture(it.data)
                },
                onDeleteClick = {
                    deletePicture(it.data)
                }
            ))
        binding.rvPhoto.adapter = photoAdapter
        binding.rvPhoto.layoutManager =
            LinearLayoutManager(this@PublishDynamicActivity, RecyclerView.HORIZONTAL, false)
        binding.rvPhoto.addItemDecoration(
            HorizontalItemDecoration(10.dp(), 0, 0)
        )

        photoTouchCallback =
            PhotoWallItemTouchHelperCallback(
                {
                    publishViewModel.mediaList.isNotEmpty()
                },
                object : PhotoWallItemTouchHelperCallback.OnItemDragCallback {

                    override fun onMoved(fromPosition: Int, toPosition: Int) {
                        //调整位置
                        publishViewModel.adjustPhotoPosition(fromPosition, toPosition)
                    }

                })
        photoTouchHelper = ItemTouchHelper(photoTouchCallback)
        photoTouchHelper.attachToRecyclerView(binding.rvPhoto)


        binding.etInput.setMaxLength(PUBLISH_DYNAMIC_MAX_LENGTH)
        binding.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            @SuppressLint("SetTextI18n")
            override fun afterTextChanged(s: Editable?) {
                val input = s?.trim()?.toString()
                if (input.isNullOrEmpty()) {
                    binding.tvInputCount.text = "0/${PUBLISH_DYNAMIC_MAX_LENGTH}"
                } else {
                    binding.tvInputCount.text = "${input.length}/${PUBLISH_DYNAMIC_MAX_LENGTH}"
                }
                notifyDynamicContentChanged()
            }
        })
    }

    override fun initComponents() {
        super.initComponents()
        PublishDynamicVideoComp(
            this,
            binding.vVideo,
            onDelete = {
                deleteVideo()
            }
        ).attach()
        TakeFromAlbumComp(
            this,
            clipParamData = null,
            onSelect = { path, uri ->
                publishViewModel.addPhoto(path, uri)
            },
            mediaType = MediaType.IMAGE,
            source = "TakePhotoAlbumComp"
        ).also {
            takePhotoAlbumComp = it
        }.attach()
        TakeFromAlbumComp(
            this,
            clipParamData = null,
            onSelect = { path, uri ->
                publishViewModel.addVideo(path, uri)
            },
            mediaType = MediaType.VIDEO,
            source = "TakeVideoAlbumComp"
        ).also {
            takeVideoAlbumComp = it
        }.attach()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        publishViewModel.mediaItemListLD.observe(this) { itemList ->
            if (publishViewModel.isVideoDynamic()) {
                binding.rvPhoto.gone()
                binding.vVideo.root.show()
                photoAdapter.submitList(emptyList())
                notifyDynamicContentChanged()
                return@observe
            }
            binding.rvPhoto.show()
            binding.vVideo.root.gone()
            photoAdapter.submitList(itemList)
            notifyDynamicContentChanged()
        }
        publishViewModel.adjustPhotoPositionLD.observe(this) {
            photoAdapter.notifyItemMoved(it.first, it.second)
        }
    }

    private fun notifyDynamicContentChanged() {
        val inputText = binding.etInput.text?.trim()
        if (!inputText.isNullOrEmpty()) {
            binding.btnPublish.isEnabled = true
            return
        }

        val mediaList = publishViewModel.mediaList
        if (mediaList.isNotEmpty()) {
            binding.btnPublish.isEnabled = true
            return
        }

        binding.btnPublish.isEnabled = false
    }

    private fun previewPicture(data: PhotoData) {
        if (data.isRemote()) {
            goImagePreviewActivity(
                this,
                arrayListOf(data.url ?: "")
            )
        } else {
            goImagePreviewActivity(
                this,
                arrayListOf(data.uri ?: "")
            )
        }
    }

    private fun deletePicture(data: PhotoData) {
        publishViewModel.removePhoto(data)
    }

    private fun deleteVideo() {
        publishViewModel.deleteVideo()
    }

    private fun publishDynamic() {
        showLoading()
        publishViewModel.publish(binding.etInput.text?.toString()).observe(this) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    finish()
                }
            }
        }
    }

    private fun showMediaSelectAction() {
        if (publishViewModel.mediaList.isNotEmpty()) {
            if (publishViewModel.isVideoDynamic()) {
                addVideo()
            } else {
                addPicture()
            }
            return
        }
        CommonTextActionDialog.Builder()
            .addItem(APP_R.id.id_common_op_select_photo, APP_R.string.common_select_photo)
            .addItem(APP_R.id.id_common_op_select_video, APP_R.string.common_select_video)
            .showCancel(true)
            .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                override fun onActionClick(viewId: Int) {
                    when (viewId) {
                        APP_R.id.id_common_op_select_photo -> {
                            addPicture()
                        }

                        APP_R.id.id_common_op_select_video -> {
                            addVideo()
                        }
                    }
                }
            }).build().show(supportFragmentManager)
    }

    private fun addPicture() {
        takePhotoAlbumComp.takeFromAlbum()
    }

    private fun addVideo() {
        takeVideoAlbumComp.takeFromAlbum()
    }

}