package com.atmob.keyboard_android.component.child.impl

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.component.base.BaseUIComponent
import com.atmob.keyboard_android.component.base.animator.ComponentAnimator
import com.atmob.keyboard_android.component.base.animator.impl.TransitionAnimator
import com.atmob.keyboard_android.component.child.IKeyboardSelectComponent
import com.atmob.keyboard_android.component.item.EmptyPlaceholderViewBinder
import com.atmob.keyboard_android.component.item.KeyboardSelectViewBinder
import com.atmob.keyboard_android.constant.Constants
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.model.EmptyPlaceholderModel
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.bridge.model.resp.KeyboardInfo
import com.atmob.keyboard_android.util.recyclerview.GridDivider
import com.blankj.utilcode.util.ConvertUtils
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter

/**
 * 键盘选择页
 */
class KeyboardSelectComponent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BaseUIComponent<IKeyboardSelectComponent>(context, attrs, defStyleAttr),
    IKeyboardSelectComponent {
    private lateinit var vBackBtn: View
    private lateinit var vList: RecyclerView
    private lateinit var vSaveBtn: View

    private lateinit var mListItems: Items
    private lateinit var mListAdapter: MultiTypeAdapter

    override fun onInflateViewId(): Int {
        return R.layout.component_keyboard_select
    }

    override fun findView(view: View) {
        vBackBtn = view.findViewById(R.id.back_btn)
        vList = view.findViewById(R.id.list)
        vSaveBtn = view.findViewById(R.id.save_btn)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun bindView(view: View) {
        vBackBtn.click {
            // 关闭选择页
            hide()
        }
        vSaveBtn.click {
            val selectKeyboard =
                mListItems.filterIsInstance<KeyboardInfo>().find {
                    it.isSelect == true
                }
            if (selectKeyboard == null) {
                return@click
            }
            // 保存，用户选择的键盘
            selectedKeyboard(selectKeyboard, onSuccess = {
                // 关闭选择器
                hide()
            })
        }

        // 配置列表
        vList.apply {
            mListItems = Items()
            mListAdapter = MultiTypeAdapter(mListItems).apply {
                // 空占位条目
                register(EmptyPlaceholderModel::class.java, EmptyPlaceholderViewBinder())
                // 键盘条目
                register(KeyboardInfo::class.java, KeyboardSelectViewBinder { item ->
                    // 先全部取消选中，再选中当前设置的键盘
                    mListItems.map { element ->
                        if (element is KeyboardInfo) {
                            element.isSelect = false
                        }
                    }
                    val targetPosition = mListItems.indexOf(item)
                    val targetItem = mListItems[targetPosition] as KeyboardInfo
                    targetItem.isSelect = true
                    notifyDataSetChanged()
                })
            }
            layoutManager =
                GridLayoutManager(context, Constants.Companion.KEYBOARD_SELECT_SPAN_COUNT)
            adapter = mListAdapter
            addItemDecoration(
                GridDivider(
                    spanCount = Constants.Companion.KEYBOARD_SELECT_SPAN_COUNT,
                    spacing = ConvertUtils.dp2px(9f)
                )
            )
        }

        setupViewModel()
        setData()
    }

    override fun getComponentAnimator(): ComponentAnimator {
        return if (Constants.COMPONENT_ANIMATOR_ENABLE) {
            TransitionAnimator()
        } else {
            super.getComponentAnimator()
        }
    }

    override fun getComponentInterfaceClazz(): Class<IKeyboardSelectComponent> {
        return IKeyboardSelectComponent::class.java
    }

    override fun onComponentShow() {
        super.onComponentShow()
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
            ?.updateKeyboardSelectPageShowing(true)
    }

    override fun onComponentHide() {
        super.onComponentHide()
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
            ?.updateKeyboardSelectPageShowing(false)
    }

    /**
     * 配置ViewModel
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setupViewModel() {
        KeyboardHolder.getKeyboardService()?.run {
            // 监听键盘列表更新
            getKeyboardViewModel().keyboardList.observe(getLifecycleOwner()) { newKeyboardList ->
                mListItems.clear()

                // 添加空占位条目
                mListItems.apply {
                    val emptyPlaceholderItemHeight = ConvertUtils.dp2px(60f - 16f)
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                }
                // 添加键盘数据
                mListItems.addAll(newKeyboardList)
                // 添加空占位条目
                mListItems.apply {
                    val emptyPlaceholderItemHeight = ConvertUtils.dp2px(60f)
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                    add(EmptyPlaceholderModel(emptyPlaceholderItemHeight))
                }

                mListAdapter.notifyDataSetChanged()
            }
            // 监听键盘模式切换
            getKeyboardViewModel().helpMode.observe(getLifecycleOwner()) {
                // 如果自己已显示，则隐藏自己
                if (getKeyboardViewModel().keyboardSelectPageShowing.value == true) {
                    hide()
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setData() {
        loadKeyboardList()
    }

    /**
     * 加载键盘数据
     */
    private fun loadKeyboardList() {
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()?.getKeyboardList()
    }

    /**
     * 选择键盘
     */
    private fun selectedKeyboard(
        selectModel: KeyboardInfo,
        onSuccess: () -> Unit
    ) {
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()?.selectedKeyboard(
            selectModel,
            onSuccess = {
                onSuccess.invoke()
            }
        )
    }
}