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

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
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.FakeComponent
import com.atmob.keyboard_android.component.base.RouteComponent
import com.atmob.keyboard_android.component.child.IAiChatComponent
import com.atmob.keyboard_android.component.child.IAiKeyboardCommonPanelComponent
import com.atmob.keyboard_android.component.child.IKeyboardGuideComponent
import com.atmob.keyboard_android.component.child.impl.ai.SuperSpeakAiChatComponent
import com.atmob.keyboard_android.component.item.AddCharacterViewBinder
import com.atmob.keyboard_android.component.item.AiKeyboardKeyViewBinder
import com.atmob.keyboard_android.constant.Constants
import com.atmob.keyboard_android.enums.HelpMode
import com.atmob.keyboard_android.enums.host.HostMainTab
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.ext.setGone
import com.atmob.keyboard_android.ext.setVisible
import com.atmob.keyboard_android.model.AddCharacterModel
import com.atmob.keyboard_android.model.AiKeyboardKeyModel
import com.atmob.keyboard_android.util.ClipboardHelper
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.KeyboardGuideDialogUtil
import com.atmob.keyboard_android.util.KeyboardGuideRecordUtil
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.LogUtil
import com.atmob.keyboard_android.util.ToastUtil
import com.atmob.keyboard_android.util.UserInfoHelper
import com.atmob.keyboard_android.util.bridge.FlutterBridgeManager
import com.atmob.keyboard_android.util.bridge.model.resp.CharacterListResp.CharacterInfo
import com.atmob.keyboard_android.util.recyclerview.GridDivider
import com.atmob.keyboard_android.widget.LongTouchContainer
import com.blankj.utilcode.util.ConvertUtils
import com.gcssloop.widget.PagerGridLayoutManager
import com.gcssloop.widget.PagerGridLayoutManager.PageListener
import com.gcssloop.widget.PagerGridSnapHelper
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter

/**
 * Ai键盘-通用类型-面板
 */
class AiKeyboardCommonPanelComponent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BaseAiKeyboardPanelComponent<IAiKeyboardCommonPanelComponent>(context, attrs, defStyleAttr),
    IAiKeyboardCommonPanelComponent {
    private lateinit var vKeyboardKeyContent: View
    private lateinit var vCommonRouteComponent: RouteComponent
    private lateinit var vPasteBarLayout: View
    private lateinit var vKeyList: RecyclerView
    private lateinit var vPasteBtn: View
    private lateinit var vDeleteBtn: LongTouchContainer
    private lateinit var vClearBtn: View
    private lateinit var vSendBtn: View

    private lateinit var vSuperSpeakAiChatComponent: SuperSpeakAiChatComponent

    private lateinit var mKeyListItems: Items
    private lateinit var mKeyListAdapter: MultiTypeAdapter

    /**
     * 键盘引导Handler
     */
    private val mKeyboardGuideHandler = Handler(Looper.getMainLooper())

    /**
     * 键盘引导，是否正在显示
     */
    private var mKeyboardGuideShowing = false

    /**
     * 当前点击的条目，用于点击重新生成时，重新生成内容
     */
    private var mCurrentClickItem: AiKeyboardKeyModel? = null

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

    override fun findView(view: View) {
        vKeyboardKeyContent = view.findViewById(R.id.keyboard_key_content)
        vCommonRouteComponent = view.findViewById(R.id.common_route_component)
        vPasteBarLayout = view.findViewById(R.id.paste_bar_layout)
        vKeyList = view.findViewById(R.id.key_list)
        vPasteBtn = view.findViewById(R.id.paste_btn)
        vDeleteBtn = view.findViewById(R.id.delete_btn)
        vClearBtn = view.findViewById(R.id.clear_btn)
        vSendBtn = view.findViewById(R.id.send_btn)
        vSuperSpeakAiChatComponent = view.findViewById(R.id.super_speak_ai_chat_component)
    }

    override fun bindView(view: View) {
        setupKeyList()
        setupActionBtn()
        setupViewModel()
        setData()
    }

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

    /**
     * 设置列表
     */
    private fun setupKeyList() {
        vKeyList.apply {
            mKeyListItems = Items()
            mKeyListAdapter = MultiTypeAdapter(mKeyListItems).apply {
                // 键盘按键条目
                register(AiKeyboardKeyModel::class.java, AiKeyboardKeyViewBinder { itemView, item ->
                    // 当前点击的条目，正在加载中，忽略点击
                    if (item.isLoading) {
                        return@AiKeyboardKeyViewBinder
                    }
                    // 其他条目正在加载中，忽略点击
                    val hasItemLoading =
                        mKeyListItems.filterIsInstance<AiKeyboardKeyModel>().filter {
                            it.isLoading
                        }.toList().isNotEmpty()
                    if (hasItemLoading) {
                        return@AiKeyboardKeyViewBinder
                    }
                    // 点击键盘按键，打开AI生成内容面板
                    if (item.isVip) {
                        // 检查是否VIP
                        UserInfoHelper.checkVip {
                            handleItemClickLogic(item)
                            LogUtil.d("Ai键盘，已经是VIP，打开Ai内容面板")
                        }
                    } else {
                        // 不需要VIP，直接打开
                        handleItemClickLogic(item)
                        LogUtil.d("Ai键盘，不需要VIP，直接进行下一步")
                    }
                })
                // 添加人设按键
                register(AddCharacterModel::class.java, AddCharacterViewBinder {
                    FlutterBridgeManager.jump2MainPage(HostMainTab.CHARACTER)
                })
            }
            if (Constants.AI_KEYBOARD_KEY_LIST_PAGE_ENABLE) {
                // 分页布局管理器
                layoutManager = PagerGridLayoutManager(
                    Constants.AI_KEYBOARD_KEY_LIST_SPAN_COUNT,
                    Constants.AI_KEYBOARD_KEY_LIST_SPAN_COUNT,
                    PagerGridLayoutManager.HORIZONTAL
                ).apply {
                    // 设置滚动监听
                    setPageListener(object : PageListener {
                        override fun onPageSizeChanged(pageSize: Int) {
                            // 当总页数确定时的回调
                        }

                        override fun onPageSelect(pageIndex: Int) {
                            // 当页面被选中时的回调（从 0 开始）
                        }
                    })
                }
                // 设置滚动辅助工具
                val pageSnapHelper = PagerGridSnapHelper().apply {
                    // 设置滚动阀值
                    setFlingThreshold(minFlingVelocity)
                }
                pageSnapHelper.attachToRecyclerView(this)
            } else {
                // 不分页，只网格
                layoutManager = GridLayoutManager(
                    context,
                    Constants.AI_KEYBOARD_KEY_LIST_SPAN_COUNT,
                    GridLayoutManager.VERTICAL,
                    false
                )
            }
            // 设置适配器
            adapter = mKeyListAdapter
            // 添加分割线
            addItemDecoration(
                GridDivider(
                    Constants.AI_KEYBOARD_KEY_LIST_SPAN_COUNT,
                    ConvertUtils.dp2px(6f)
                )
            )
        }
    }

    /**
     * 设置操作按钮
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun setupActionBtn() {
        // 粘贴
        vPasteBtn.click {
            // 获取用户剪切板中的数据
            val text = ClipboardHelper.getUserClipboardData();
            if (text.isBlank()) {
                return@click
            }
            KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let {
                InputMethodUtil.inputText(it.currentInputConnection, text)
            }
        }

        // 删除
        vDeleteBtn.setOnLongPressListener {
            KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let {
                InputMethodUtil.deleteInput(it.currentInputConnection)
            }
        }

        // 清空
        vClearBtn.click {
            KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let {
                InputMethodUtil.clearInput(it.currentInputConnection)
            }
        }

        // 发送
        vSendBtn.click {
            KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let {
                InputMethodUtil.clickSendBtn(it)
            }
        }
    }

    /**
     * 配置ViewModel
     */
    private fun setupViewModel() {
        KeyboardHolder.getKeyboardService()?.run {
            // 监听人设列表更新
            getKeyboardViewModel().characterList.observe(getLifecycleOwner()) {
                renderList(it)
            }
            // 监听帮助模式更新，切换键盘
            getKeyboardViewModel().helpMode.observe(getLifecycleOwner()) { newMode ->
                // 隐藏AI生成内容面板
                controlAiChatPageShowing(false)
                // 重新加载按键列表
                if (HelpMode.OPEN_REMARKS != newMode) {
                    // 非开场白类型
                    loadKeyList()
                }
            }
            // 监听键盘选择切换
            getKeyboardViewModel().currentKeyboardInfo.observe(getLifecycleOwner()) { newKeyboard ->
                loadKeyList()
            }
            // 监听教你说的Ai内容生成页，是否显示
            getKeyboardViewModel().superSpeakAiChatPageShowing.observe(getLifecycleOwner()) { isShowing ->
                // 显示Ai内容生成页，隐藏键盘列表
                if (isShowing) {
                    vKeyList.setGone()
                } else {
                    // Ai生成页关闭，则显示键盘列表
                    vKeyList.setVisible()
                }
            }
            // 监听生成的Ai内容
            getKeyboardViewModel().chatSuperReplyResult.observe(getLifecycleOwner()) {
                if (it.isBlank()) {
                    return@observe
                }
                // 生成的内容，直接添加到输入框
                KeyboardHolder.getKeyboardService()?.asInputMethodService()?.let { service ->
                    InputMethodUtil.inputText(service.currentInputConnection, it)
                }
            }
        }
    }

    /**
     * 填充数据
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setData() {
        // 监听重新生成按钮点击
        vSuperSpeakAiChatComponent.setOnActionClickListener(object :
            AiChatComponent.OnActionClickListener {
            override fun onReGenerateClick() {
                mCurrentClickItem?.let {
                    // 重新生成内容
                    handleItemClickLogic(it)
                }
            }
        })
    }

    /**
     * 加载按键列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun loadKeyList() {
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
            ?.getCharacterList()
    }

    /**
     * 根据数据,渲染列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun renderList(characterList: List<CharacterInfo>) {
        val newList = characterList.map {
            AiKeyboardKeyModel(
                // 显示的文本 = 表情 + 名字
                text = "${it.emoji} ${it.name}",
                // 拓展字段，存储人设Id
                payload = it.id,
                // 是否需要VIP
                isVip = it.isVip
            )
        }
        mKeyListItems.clear()
        // 添加按键列表
        mKeyListItems.addAll(newList)
        // 添加人设按钮
        mKeyListItems.add(AddCharacterModel())
        mKeyListAdapter.notifyDataSetChanged()

        // 显示键盘引导页
        tryShowKeyboardGuide()
    }

    /**
     * 显示键盘引导
     */
    private fun tryShowKeyboardGuide() {
        val action = Runnable {
            // 正在显示，忽略
            if (mKeyboardGuideShowing) {
                return@Runnable
            }

            // 不是第一次引导，忽略
            if (!KeyboardGuideRecordUtil.isFirstShowKeyboardGuide()) {
                return@Runnable
            }

            val targetIndex = Constants.KEYBOARD_GUIDE_KEY_POSITION

            // 获取所有按键数据
            val keyList = mKeyListItems.filterIsInstance<AiKeyboardKeyModel>().toList()
            if (keyList.isEmpty()) {
                return@Runnable
            }
            // 目标超出范围，忽略
            if (targetIndex > keyList.size - 1) {
                return@Runnable
            }

            // 条目数据
            val itemData = keyList[targetIndex]
            // 通过position，获取ViewHolder
            val viewHolder =
                vKeyList.findViewHolderForAdapterPosition(targetIndex)

            // 找到目标条目，则显示引导
            if (viewHolder != null) {
                val itemView = viewHolder.itemView
                KeyboardGuideDialogUtil.showGuideDialog(
                    itemView,
                    itemData,
                    object : IKeyboardGuideComponent.OnActionCallback {
                        override fun onFinishGuide() {
                            mKeyboardGuideShowing = false
                            KeyboardGuideRecordUtil.setFirstShowKeyboardGuide(false)
                        }
                    })
                mKeyboardGuideShowing = true
            }
        }
        mKeyboardGuideHandler.postDelayed(action, 300)
    }

    /**
     * 控制Ai生成内容面板，是否显示
     */
    override fun controlAiChatPageShowing(isShow: Boolean) {
        // 切换到Ai生成内容页
        if (isShow) {
            vCommonRouteComponent.routeChildComponent(IAiChatComponent::class.java)
        } else {
            // 切换回键盘页
            vCommonRouteComponent.routeChildComponent(FakeComponent::class.java, true)
        }
    }

    /**
     * 处理条目点击逻辑
     *
     * @param item 当前点击的条目的数据
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun handleItemClickLogic(
        item: AiKeyboardKeyModel
    ) {
        // 判断帮助模式
        val helpMode = KeyboardHolder.getKeyboardService()
            ?.getKeyboardViewModel()?.helpMode?.value
        if (helpMode == null) {
            return
        }

        // 保存当前点击项的数据
        this.mCurrentClickItem = item

        LogUtil.d("当前帮助模式 => $helpMode")

        // 获取剪切板内容
        val clipboardText =
            KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()?.userClipboardData?.value
                ?: ""
        if (clipboardText.isBlank()) {
            ToastUtil.showToast(context.resources.getString(R.string.no_clipboard_data_tip))
            return
        }

        if (HelpMode.HELP_CHAT == helpMode) {
            // 帮聊只会生成一条内容，直接添加到输入框
            doChatSuperReply(item.payload, startCallback = {
                // 生成开始，显示Loading
                item.isLoading = true
                mKeyListAdapter.notifyDataSetChanged()
            }, finishCallback = {
                // 生成结束，关闭Loading
                item.isLoading = false
                mKeyListAdapter.notifyDataSetChanged()
            })
        } else {
            // 教你说和开场白，有多条数据，需要添加到列表中展示
            if (HelpMode.TEACH_YOU_SAY == helpMode) {
                doChatSuperSpeak(item.payload)
            } else if (HelpMode.OPEN_REMARKS == helpMode) {
                doChatPrologue(item.payload)
            }
        }
    }
}