package com.useasy.callsdk.demo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.useasy.callsdk.CallSDK
import com.useasy.callsdk.bean.AgentConfig
import com.useasy.callsdk.bean.DisplayNumber
import com.useasy.callsdk.demo.adapter.DisplayNumberAdapter
import com.useasy.callsdk.demo.adapter.NumberGroupAdapter
import com.useasy.callsdk.listener.AgentConfigListener
import com.useasy.callsdk.listener.DisplayNumberListListener
import com.useasy.callsdk.listener.NumberGroupListListener
import com.useasy.callsdk.utils.Loger

/**
 * 通话设置页面
 * 用于配置外显号码或外显号码组
 */
class CallSettingsActivity : BaseActivity() {

    companion object {
        const val EXTRA_AGENT_CONFIG = "extra_agent_config"
    }

    private var agentConfig: AgentConfig? = null
    private lateinit var llEnterpriseSetting: LinearLayout
    private lateinit var llEnterpriseGroupSetting: LinearLayout
    private lateinit var tvCurrentNumber: TextView
    private lateinit var tvCurrentGroup: TextView
    private lateinit var rvDisplayNumbers: RecyclerView
    private lateinit var rvNumberGroups: RecyclerView

    private var displayNumberAdapter: DisplayNumberAdapter? = null
    private var numberGroupAdapter: NumberGroupAdapter? = null
    private var selectedNumber: String? = null
    private var selectedNumberGroupId: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_call_settings)

        // 直接获取传递的对象（AgentConfig 已实现 Parcelable）
        agentConfig = intent.getParcelableExtra(EXTRA_AGENT_CONFIG)

        initViews()
        setupToolbar()
        loadConfig()
    }

    private fun initViews() {
        llEnterpriseSetting = findViewById(R.id.ll_enterprise_setting)
        llEnterpriseGroupSetting = findViewById(R.id.ll_enterprise_group_setting)
        tvCurrentNumber = findViewById(R.id.tv_current_number)
        tvCurrentGroup = findViewById(R.id.tv_current_group)
        rvDisplayNumbers = findViewById(R.id.rv_display_numbers)
        rvNumberGroups = findViewById(R.id.rv_number_groups)

        rvDisplayNumbers.layoutManager = LinearLayoutManager(this)
        rvNumberGroups.layoutManager = LinearLayoutManager(this)
    }

    private fun setupToolbar() {
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
        toolbar.setNavigationOnClickListener {
            finish()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        // 在外显号码或号码组设置时显示确定按钮
        if (llEnterpriseSetting.visibility == View.VISIBLE || llEnterpriseGroupSetting.visibility == View.VISIBLE) {
            menuInflater.inflate(R.menu.menu_call_settings, menu)
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_confirm) {
            if (llEnterpriseSetting.visibility == View.VISIBLE) {
                saveSelectNumber()
            } else if (llEnterpriseGroupSetting.visibility == View.VISIBLE) {
                saveNumberGroup()
            }
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun loadConfig() {
        val config = agentConfig ?: run {
            Toast.makeText(this, "未获取到配置信息", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        val callConfig = config.agentCallConfig ?: run {
            Toast.makeText(this, "配置信息不完整", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        val callerStrategy = callConfig.callerStrategy
        if (callerStrategy != null && callerStrategy.isNotEmpty()) {
            when {
                callerStrategy.contains("enterprise") -> {
                    // 配置的是外显号码
                    val selectNumber = callConfig.selectNumber
                    selectedNumber = selectNumber
                    Loger.dTag("CallSettingsActivity", "配置的是外显号码: $selectNumber")
                    llEnterpriseSetting.visibility = View.VISIBLE
                    invalidateOptionsMenu()

                    tvCurrentNumber.text = "当前外显号码: ${selectNumber ?: "未设置"}"

                    loadDisplayNumberList()
                }

                callerStrategy.contains("enterpriseGroup") -> {
                    // 配置的是外显号码组
                    val numberGroupId = callConfig.numberGroup
                    selectedNumberGroupId = numberGroupId
                    Loger.dTag("CallSettingsActivity", "配置的是外显号码组: $numberGroupId")
                    llEnterpriseGroupSetting.visibility = View.VISIBLE
                    invalidateOptionsMenu()

                    tvCurrentGroup.text = "当前号码组: ${numberGroupId ?: "未设置"}"

                    // 加载号码组列表
                    loadNumberGroupList()
                }

            }
        }
    }

    /**
     * 加载外显号码组列表
     */
    private fun loadNumberGroupList() {
        CallSDK.queryNumberGroupList(
            page = -1, pageSize = 999, listener = object : NumberGroupListListener {
                override fun onSuccess(response: com.useasy.callsdk.bean.NumberGroupListResponse?) {
                    Handler(Looper.getMainLooper()).post {
                        val groups = response?.list ?: emptyList()
                        if (groups.isEmpty()) {
                            Toast.makeText(
                                this@CallSettingsActivity,
                                "暂无号码组",
                                Toast.LENGTH_SHORT
                            ).show()
                            return@post
                        }

                        // 更新当前号码组显示名称
                        selectedNumberGroupId?.let { currentId ->
                            val currentGroup = groups.find { it.id == currentId }
                            val displayName =
                                currentGroup?.groupName ?: currentGroup?.id ?: "未设置"
                            tvCurrentGroup.text = "当前号码组: $displayName"
                        }

                        // 显示号码组列表
                        numberGroupAdapter = NumberGroupAdapter(
                            numberGroups = groups,
                            selectedGroupId = selectedNumberGroupId,
                            onItemClick = { group ->
                                selectedNumberGroupId = group.id
                                // 更新当前号码组显示
                                val displayName = group.groupName ?: group.id ?: "未设置"
                                tvCurrentGroup.text = "当前号码组: $displayName"
                                Loger.dTag(
                                    "CallSettingsActivity",
                                    "选中号码组: ${group.groupName}, id: ${group.id}"
                                )
                            })
                        rvNumberGroups.adapter = numberGroupAdapter
                        // 禁用 RecyclerView 的嵌套滚动，让 NestedScrollView 处理滚动
                        rvNumberGroups.isNestedScrollingEnabled = false
                    }
                }

                override fun onFailed(errorMsg: String?) {
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(
                            this@CallSettingsActivity,
                            "加载号码组列表失败: $errorMsg",
                            Toast.LENGTH_SHORT
                        ).show()
                        Loger.eTag("CallSettingsActivity", "加载号码组列表失败: $errorMsg")
                    }
                }
            })
    }

    /**
     * 加载外显号码列表
     */
    private fun loadDisplayNumberList() {
        CallSDK.queryDisplayNumberList(object : DisplayNumberListListener {
            override fun onSuccess(numbers: List<DisplayNumber>?) {
                Handler(Looper.getMainLooper()).post {
                    val numberList = numbers ?: emptyList()
                    if (numberList.isEmpty()) {
                        Toast.makeText(
                            this@CallSettingsActivity,
                            "暂无外显号码",
                            Toast.LENGTH_SHORT
                        ).show()
                        return@post
                    }

                    // 更新当前外显号码显示
                    selectedNumber?.let { currentNumber ->
                        val currentDisplayNumber = numberList.find {
                            it.number == currentNumber || it.id == currentNumber
                        }
                        val displayText = currentDisplayNumber?.number ?: currentNumber
                        tvCurrentNumber.text = "当前外显号码: $displayText"
                    }

                    // 显示外显号码列表
                    displayNumberAdapter = DisplayNumberAdapter(
                        numbers = numberList,
                        selectedNumber = selectedNumber,
                        onItemClick = { number ->
                            selectedNumber = number.number ?: number.id
                            // 更新当前外显号码显示
                            val displayText = number.number ?: number.id ?: "未设置"
                            tvCurrentNumber.text = "当前外显号码: $displayText"
                            Loger.dTag(
                                "CallSettingsActivity",
                                "选中外显号码: ${number.number}, id: ${number.id}"
                            )
                        })
                    rvDisplayNumbers.adapter = displayNumberAdapter
                }
            }

            override fun onFailed(errorMsg: String?) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this@CallSettingsActivity,
                        "加载外显号码列表失败: $errorMsg",
                        Toast.LENGTH_SHORT
                    ).show()
                    Loger.eTag("CallSettingsActivity", "加载外显号码列表失败: $errorMsg")
                }
            }
        })
    }

    /**
     * 保存选中的外显号码
     */
    private fun saveSelectNumber() {
        val agentId = agentConfig?._id
        val selectNumber = displayNumberAdapter?.getSelectedNumber()

        if (agentId.isNullOrEmpty()) {
            Toast.makeText(this, "无法获取座席ID", Toast.LENGTH_SHORT).show()
            return
        }

        if (selectNumber.isNullOrEmpty()) {
            Toast.makeText(this, "请选择外显号码", Toast.LENGTH_SHORT).show()
            return
        }

        // 调用更新接口
        CallSDK.updateAgentSelectNumber(selectNumber, object : AgentConfigListener {
            override fun onSuccess(agentConfig: AgentConfig?) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(this@CallSettingsActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    Loger.dTag("CallSettingsActivity", "更新外显号码成功")
                    finish()
                }
            }

            override fun onFailed(errorMsg: String?) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this@CallSettingsActivity,
                        "设置失败: $errorMsg",
                        Toast.LENGTH_SHORT
                    ).show()
                    Loger.eTag("CallSettingsActivity", "更新外显号码失败: $errorMsg")
                }
            }
        })
    }

    /**
     * 保存选中的号码组
     */
    private fun saveNumberGroup() {
        val agentId = agentConfig?._id
        val numberGroupId = numberGroupAdapter?.getSelectedGroupId()
        val numberGroupName = numberGroupAdapter?.getSelectedGroupName()

        if (agentId.isNullOrEmpty()) {
            Toast.makeText(this, "无法获取座席ID", Toast.LENGTH_SHORT).show()
            return
        }

        if (numberGroupId.isNullOrEmpty()) {
            Toast.makeText(this, "请选择号码组", Toast.LENGTH_SHORT).show()
            return
        }

        CallSDK.updateAgentNumberGroupByName(numberGroupName, object : AgentConfigListener {
            override fun onSuccess(agentConfig: AgentConfig?) {

            }

            override fun onFailed(errorMsg: String?) {

            }

        })

        // 调用更新接口
        CallSDK.updateAgentNumberGroupById(numberGroupId, object : AgentConfigListener {
            override fun onSuccess(agentConfig: AgentConfig?) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(this@CallSettingsActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    Loger.dTag("CallSettingsActivity", "更新号码组成功")
                    finish()
                }
            }

            override fun onFailed(errorMsg: String?) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this@CallSettingsActivity,
                        "设置失败: $errorMsg",
                        Toast.LENGTH_SHORT
                    ).show()
                    Loger.eTag("CallSettingsActivity", "更新号码组失败: $errorMsg")
                }
            }
        })
    }
}

