package com.adealink.weparty.setting.helpcenter

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.GridLayoutManager
import com.adealink.frame.aab.util.getCompatDimension
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.mediapicker.imageselect.comp.TakeFromAlbumComp
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.GridSpacingItemDecoration
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.constant.HELP_CENTER_CONTENT_MAX_LENGTH
import com.adealink.weparty.module.image.data.PhotoData
import com.adealink.weparty.module.setting.Setting
import com.adealink.weparty.setting.R
import com.adealink.weparty.setting.databinding.ActivityHelpCenterBinding
import com.adealink.weparty.setting.helpcenter.adapter.AddPictureItemViewBinder
import com.adealink.weparty.setting.helpcenter.adapter.PictureItemViewBinder
import com.adealink.weparty.setting.helpcenter.data.AddPictureItemData
import com.adealink.weparty.setting.helpcenter.data.BasePictureItemData
import com.adealink.weparty.setting.helpcenter.viewmodel.HelpCenterViewModel
import com.adealink.weparty.util.QMUIKeyboardHelper
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.goImagePreviewActivity
import com.adealink.weparty.R as APP_R

@RouterUri(
    path = [Setting.HelpCenter.PATH],
    desc = "帮助中心"
)
class HelpCenterActivity : BaseActivity() {

    companion object {
        private const val PICTURE_SPAN = 3
    }

    private val binding by viewBinding(ActivityHelpCenterBinding::inflate)

    private val pictureAdapter by fastLazy { MultiTypeListAdapter<BasePictureItemData>() }

    private val viewModel by viewModels<HelpCenterViewModel>()

    private lateinit var takeFromAlbumComp: TakeFromAlbumComp

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    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.btnSubmit.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = getCompatDimension(APP_R.dimen.main_bottom_bar_margin_bottom).toInt()
        }
        binding.clContent.setPadding(
            0, 0, 0,
            getCompatDimension(APP_R.dimen.common_button_height).toInt() + getCompatDimension(APP_R.dimen.main_bottom_bar_margin_bottom).toInt() + 24.dp()
        )

        binding.etInput.setMaxLength(HELP_CENTER_CONTENT_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.btnSubmit.isEnabled = false
                    binding.tvInputCount.text = "0/${HELP_CENTER_CONTENT_MAX_LENGTH}"
                } else {
                    binding.btnSubmit.isEnabled = true
                    binding.tvInputCount.text = "${input.length}/${HELP_CENTER_CONTENT_MAX_LENGTH}"
                }
            }
        })
        binding.btnSubmit.isEnabled = false

        pictureAdapter.register(
            AddPictureItemViewBinder {
                addPicture()
            }
        )
        pictureAdapter.register(
            PictureItemViewBinder(
                this@HelpCenterActivity,
                onItemClick = {
                    previewPicture(it.data)
                },
                onDeleteClick = {
                    deletePicture(it.data)
                }
            ))
        binding.rvPicture.adapter = pictureAdapter
        binding.rvPicture.layoutManager = GridLayoutManager(this, PICTURE_SPAN)
        binding.rvPicture.addItemDecoration(
            GridSpacingItemDecoration(PICTURE_SPAN, 4.dp(), 4.dp(), false)
        )

        binding.btnSubmit.onClick {
            submit()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.pictureItemListLD.observe(this) {
            pictureAdapter.submitList(it)
        }
    }

    override fun loadData() {
        super.loadData()
        pictureAdapter.submitList(
            listOf(AddPictureItemData)
        )
    }

    override fun initComponents() {
        super.initComponents()
        TakeFromAlbumComp(
            this,
            clipParamData = null,
            onSelect = { path, uri ->
                viewModel.addPicture(path, uri)
            }
        ).also {
            takeFromAlbumComp = it
        }.attach()
    }

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

    private fun previewPicture(data: PhotoData) {
        val uri = data.uri
        if (uri.isNullOrEmpty()) {
            return
        }
        goImagePreviewActivity(
            this,
            arrayListOf(uri)
        )
    }

    private fun deletePicture(data: PhotoData) {
        viewModel.removePicture(data)
    }

    private fun submit() {
        val content = binding.etInput.text?.trim()?.toString()
        if (content.isNullOrEmpty()) {
            showToast(getCompatString(R.string.setting_feedback_input_content))
            return
        }
        showLoading()
        viewModel.submit(content).observe(this) { rlt ->
            dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    showToast(APP_R.string.common_success)
                    finish()
                }
            }
        }
    }

    override fun onDestroy() {
        binding.etInput.clearFocus()
        QMUIKeyboardHelper.hideKeyboard(binding.etInput)
        super.onDestroy()
    }

}