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.FakeComponent
import com.atmob.keyboard_android.component.base.RouteComponent
import com.atmob.keyboard_android.component.child.IAiChatComponent
import com.atmob.keyboard_android.component.child.IAiKeyboardProloguePanelComponent
import com.atmob.keyboard_android.component.child.impl.ai.PrologueAiChatComponent
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.ext.click
import com.atmob.keyboard_android.ext.setGone
import com.atmob.keyboard_android.ext.setVisible
import com.atmob.keyboard_android.model.AiKeyboardKeyModel
import com.atmob.keyboard_android.util.InputMethodUtil
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.recyclerview.GridDivider
import com.atmob.keyboard_android.widget.LongTouchContainer
import com.atmob.keyboard_android.widget.indicator.TabPagerTitleView
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
import net.lucode.hackware.magicindicator.MagicIndicator
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator

/**
 * Ai键盘-开场白类型-面板
 */
class AiKeyboardProloguePanelComponent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BaseAiKeyboardPanelComponent<IAiKeyboardProloguePanelComponent>(context, attrs, defStyleAttr),
    IAiKeyboardProloguePanelComponent {
    private lateinit var vTabBarLayout: View
    private lateinit var vMagicIndicator: MagicIndicator
    private lateinit var vKeyboardKeyContent: View
    private lateinit var vPrologueRouteComponent: RouteComponent
    private lateinit var vKeyList: RecyclerView
    private lateinit var vDeleteBtn: LongTouchContainer
    private lateinit var vClearBtn: View
    private lateinit var vSendBtn: View

    private lateinit var vPrologueAiChatComponent: PrologueAiChatComponent

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

    /**
     * Tab列表
     */
    private lateinit var mTabList: MutableList<String>

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

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

    override fun findView(view: View) {
        vTabBarLayout = view.findViewById(R.id.tar_bar_layout)
        vMagicIndicator = view.findViewById(R.id.magic_indicator)
        vKeyboardKeyContent = view.findViewById(R.id.keyboard_key_content)
        vPrologueRouteComponent = view.findViewById(R.id.prologue_route_component)
        vKeyList = view.findViewById(R.id.key_list)
        vDeleteBtn = view.findViewById(R.id.delete_btn)
        vClearBtn = view.findViewById(R.id.clear_btn)
        vSendBtn = view.findViewById(R.id.send_btn)
        vPrologueAiChatComponent = view.findViewById(R.id.prologue_ai_chat_component)
    }

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

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

    /**
     * 配置Tab栏
     */
    private fun setupTabBar() {
        // 初始化Tab列表
        mTabList = mutableListOf()

        // 配置指示器
        vMagicIndicator.setNavigator(CommonNavigator(context).apply {
            // 滚动中心点
            scrollPivotX = 0.35f
            // 设置适配器
            setAdapter(object : CommonNavigatorAdapter() {
                override fun getCount(): Int {
                    return mTabList.size
                }

                override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                    val titleView = object : TabPagerTitleView(context) {
                        override fun onSelected(index: Int, totalCount: Int) {
                            super.onSelected(index, totalCount)
                            // 选中Tab，设置为粗体
                            setBoldStyle(true)
                        }

                        override fun onDeselected(index: Int, totalCount: Int) {
                            super.onDeselected(index, totalCount)
                            // 不选中Tab，设置为普通体
                            setBoldStyle(false)
                        }
                    }
                    // Tab文字
                    titleView.setText(mTabList[index])
                    // Tab未选中时的字体颜色
                    titleView.setTextColor(context.resources.getColor(R.color.text_color_secondary))
                    // Tab选中时的字体颜色
                    titleView.setClipColor(context.resources.getColor(R.color.text_color_primary))
                    // 字体大小
                    titleView.textSize = ConvertUtils.dp2px(12f).toFloat()
                    // 设置padding，让文字距离背景有一定间距
                    val paddingHorizontal = ConvertUtils.dp2px(18f)
                    titleView.setPadding(paddingHorizontal, 0, paddingHorizontal, 0)
                    // 点击Tab，切换页面
                    titleView.setOnClickListener(object : OnClickListener {
                        override fun onClick(v: View?) {
                            handleTabClick(index)
                        }
                    })
                    return titleView
                }

                override fun getIndicator(context: Context): IPagerIndicator {
                    val indicator = LinePagerIndicator(context)
                    val navigatorHeight =
                        context.resources.getDimension(R.dimen.common_navigator_height)
                    val borderWidth = UIUtil.dip2px(context, 1.0).toFloat()
                    val lineHeight = navigatorHeight - 2 * borderWidth
                    indicator.lineHeight = lineHeight
                    indicator.roundRadius = lineHeight / 2
                    indicator.yOffset = borderWidth
                    // 指示器的背景颜色
                    indicator.setColors(context.resources.getColor(R.color.bg_tab_indicator_selected))
                    return indicator
                }
            })
        })
    }

    /**
     * 设置列表
     */
    private fun setupKeyList() {
        vKeyList.apply {
            mKeyListItems = Items()
            mKeyListAdapter = MultiTypeAdapter(mKeyListItems).apply {
                register(AiKeyboardKeyModel::class.java, AiKeyboardKeyViewBinder { itemView, item ->
                    // 点击键盘按键，打开AI生成内容面板
                    if (item.isVip) {
                        // 检查是否VIP
                        UserInfoHelper.checkVip {
                            handleItemClickLogic(item)
                            LogUtil.d("Ai键盘，已经是VIP，打开Ai内容面板")
                        }
                    } else {
                        // 不需要VIP，直接打开
                        handleItemClickLogic(item)
                        LogUtil.d("Ai键盘，不需要VIP，直接进行下一步")
                    }
                })
            }
            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() {
        // 删除
        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().prologueList.observe(getLifecycleOwner()) { list ->
                // 更新Tab列表
                val tabList = list.map {
                    it.title
                }.toList()
                mTabList.clear()
                mTabList.addAll(tabList)
                // 刷新Tab栏
                vMagicIndicator.navigator.notifyDataSetChanged()
                LogUtil.d("开场白列表更新，刷新Tab栏 => ${tabList.size}个Tab")
                // 默认选中第一个Tab
                handleTabClick(0)
            }
            // 监听Tab切换，更新键盘列表
            getKeyboardViewModel().currentPrologueTab.observe(getLifecycleOwner()) { newTab ->
                // 切换Tab
                vMagicIndicator.onPageSelected(mTabList.indexOf(newTab))
                // 关闭Ai内容生成面板
                controlAiChatPageShowing(false)
                // 根据Tab，重新加载数据
                loadKeyListByTab(newTab)
            }
            // 监听开场白的Ai内容生成页，是否显示
            getKeyboardViewModel().prologueAiChatPageShowing.observe(getLifecycleOwner()) { isShowing ->
                // 显示Ai内容生成页，隐藏键盘列表
                if (isShowing) {
                    vKeyList.setGone()
                } else {
                    // Ai生成页关闭，则显示键盘列表
                    vKeyList.setVisible()
                }
            }
        }
    }

    /**
     * 填充数据
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setData() {
        // 拉取开场白列表
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()?.getPrologueList()
        // 监听重新生成按钮点击
        vPrologueAiChatComponent.setOnActionClickListener(object :
            AiChatComponent.OnActionClickListener {
            override fun onReGenerateClick() {
                mCurrentClickItem?.let {
                    // 重新生成内容
                    handleItemClickLogic(it)
                }
            }
        })
    }

    /**
     * 处理Tab切换
     */
    private fun handleTabClick(index: Int) {
        // 如果没有更新，不需要切换
        val newTab = mTabList[index]
        val currentTab = KeyboardHolder.getKeyboardService()
            ?.getKeyboardViewModel()?.currentPrologueTab?.value
        if (currentTab == newTab) {
            return
        }
        // 更新Tab
        KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
            ?.updateCurrentPrologueTab(newTab)
    }

    /**
     * 根据Tab，加载按键列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun loadKeyListByTab(tab: String) {
        val list = KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
            ?.filterPrologueListByTab(tab) ?: listOf()
        val newList = list.map {
            AiKeyboardKeyModel(
                // 显示的文本 = 名字
                text = it.name,
                // 拓展字段，存储话题名字
                payload = it.name,
                // 是否需要VIP
                isVip = false
            )
        }.toList()
        mKeyListItems.clear()
        mKeyListItems.addAll(newList)
        mKeyListAdapter.notifyDataSetChanged()
    }

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

    /**
     * 处理条目点击逻辑
     */
    private fun handleItemClickLogic(item: AiKeyboardKeyModel) {
        // 判断帮助模式
        val helpMode = KeyboardHolder.getKeyboardService()
            ?.getKeyboardViewModel()?.helpMode?.value
        if (helpMode == null) {
            return
        }

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

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

        // 获取剪切板内容
        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)
        } else {
            // 教你说和开场白，有多条数据，需要添加到列表中展示
            if (HelpMode.TEACH_YOU_SAY == helpMode) {
                doChatSuperSpeak(item.payload)
            } else if (HelpMode.OPEN_REMARKS == helpMode) {
                doChatPrologue(item.payload)
            }
        }
    }
}