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.LinearLayoutManager
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.IAiChatComponent
import com.atmob.keyboard_android.component.item.AiChatViewBinder
import com.atmob.keyboard_android.component.item.AiGenerateLoadingViewBinder
import com.atmob.keyboard_android.component.item.EmptyPlaceholderViewBinder
import com.atmob.keyboard_android.constant.Constants
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.model.AiChatModel
import com.atmob.keyboard_android.model.AiGenerateLoadingModel
import com.atmob.keyboard_android.model.EmptyPlaceholderModel
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.recyclerview.LinearDivider
import com.blankj.utilcode.util.ConvertUtils
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter

/**
 * Ai对话组件，基类，子类有教你说和开场白
 */
abstract class AiChatComponent<T : IAiChatComponent> @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BaseUIComponent<T>(context, attrs, defStyleAttr) {
    private lateinit var vBackBtn: View
    protected lateinit var vReGenerateBtn: View
    private lateinit var vChatList: RecyclerView

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

    private var mOnActionClickListener: OnActionClickListener? = null

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

    override fun findView(view: View) {
        vBackBtn = view.findViewById(R.id.back_btn)
        vReGenerateBtn = view.findViewById(R.id.re_generate_btn)
        vChatList = view.findViewById(R.id.chat_list)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun bindView(view: View) {
        vBackBtn.click {
            // 关闭面板
            hide()
        }
        vReGenerateBtn.click {
            // 重新生成
            mOnActionClickListener?.onReGenerateClick()
        }
        vChatList.apply {
            mListItems = Items()
            mListAdapter = MultiTypeAdapter(mListItems).apply {
                // 空占位条目
                register(EmptyPlaceholderModel::class.java, EmptyPlaceholderViewBinder())
                // 加载中条目
                register(AiGenerateLoadingModel::class.java, AiGenerateLoadingViewBinder())
                // 生成内容条目
                register(AiChatModel::class.java, AiChatViewBinder { item ->
                    // 先全部取消选中
                    mListItems.filterIsInstance<AiChatModel>().map {
                        it.isSelected = false
                    }
                    // 再选中当前选择的
                    val targetPosition = mListItems.indexOf(item)
                    val targetItem = mListItems[targetPosition]
                    if (targetItem is AiChatModel) {
                        targetItem.isSelected = true
                        notifyDataSetChanged()
                        // 设置文本到输入框中
                        KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let {
                            InputMethodUtil.inputText(it.currentInputConnection, targetItem.text)
                        }
                    }
                })
            }
            // 方向
            val orientation = RecyclerView.VERTICAL
            layoutManager = LinearLayoutManager(context, orientation, false)
            adapter = mListAdapter
            // 分割线
            addItemDecoration(LinearDivider(ConvertUtils.dp2px(8f), orientation, true))
        }

        setupViewModel()
    }

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

    /**
     * 配置ViewModel，子类重写
     */
    protected abstract fun setupViewModel()

    /**
     * 加载Ai内容列表
     */
    @SuppressLint("NotifyDataSetChanged")
    protected fun loadAiList(list: List<String>) {
        mListItems.clear()
        mListItems.apply {
            // 空占位条目
            add(EmptyPlaceholderModel(ConvertUtils.dp2px(40f)))
            // 添加生成内容条目
            val aiChatItemList = list.map {
                AiChatModel(
                    text = it
                )
            }.toList()
            // 添加Loading条目
            if (aiChatItemList.isEmpty()) {
                add(AiGenerateLoadingModel())
                add(AiGenerateLoadingModel())
                add(AiGenerateLoadingModel())
            } else {
                // 生成条目
                addAll(aiChatItemList)
            }
        }
        mListAdapter.notifyDataSetChanged()
    }

    interface OnActionClickListener {
        /**
         * 重新生成
         */
        fun onReGenerateClick()
    }

    /**
     * 设置操作回调
     */
    fun setOnActionClickListener(listener: OnActionClickListener) {
        this.mOnActionClickListener = listener
    }
}