package com.example.defenseapplication.liveVideo

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.LinkedUser
import com.example.defenseapplication.adapter.LinkedUserAdapter
import com.example.defenseapplication.bean.DeleteDeviceUserRequest
import com.example.defenseapplication.bean.DeviceUserBean
import com.example.defenseapplication.bean.FamilyMembersBean
import com.example.defenseapplication.databinding.LinkedUserActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.DeviceUserUpdateEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.gyf.immersionbar.ImmersionBar
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
//关联用户
class LinkedUserActivity : AppCompatActivity() {

    private lateinit var binding: LinkedUserActivityBinding
    private lateinit var adapter: LinkedUserAdapter
    private val fullUserList = mutableListOf<LinkedUser>()
    private val userList = mutableListOf<LinkedUser>()
    private var mode: Int = MODE_SETTINGS

    companion object {
        const val EXTRA_MODE = "extra_mode"
        const val MODE_SETTINGS = 0
        const val MODE_PERSONAL = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = LinkedUserActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        mode = intent.getIntExtra(EXTRA_MODE, MODE_SETTINGS)

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()

        initView()
        initData()
        initListener()
        setupModeUI()
        DeviceUserUpdateEvent.addListener(deviceUserUpdateListener)
    }

    private val deviceUserUpdateListener = object : DeviceUserUpdateEvent.DeviceUserUpdateListener {
        override fun onDeviceUserUpdated() {
            fetchUserList()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        DeviceUserUpdateEvent.removeListener(deviceUserUpdateListener)
    }

    private fun initView() {
        adapter = LinkedUserAdapter(
            isUnlinkMode = mode == MODE_SETTINGS,
            onItemClick = { user, position ->
                val intent = Intent(this, UserDetailsActivity::class.java).apply {
                    putExtra("userId", user.userId)
                    putExtra("deleteText", if (mode == MODE_SETTINGS) getString(R.string.unlink) else getString(R.string.delete))
                    putExtra("isUnlinkMode", mode == MODE_SETTINGS)
                }
                startActivity(intent)
            }
        )

        (binding.rvLinkedUser as RecyclerView).layoutManager = LinearLayoutManager(this)

        binding.swipeRefresh.setOnRefreshListener {
            fetchUserList()
        }

        binding.rvLinkedUser.setSwipeMenuCreator { leftMenu, rightMenu, position ->
            if (mode == MODE_SETTINGS) {
                val unlinkItem = SwipeMenuItem(this@LinkedUserActivity).apply {
                    setText(getString(R.string.unlink))
                    setBackgroundColor(getColor(R.color.red))
                    setTextColor(getColor(R.color.white))
                    width = 200
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                }
                rightMenu.addMenuItem(unlinkItem)
            } else {
                val deleteItem = SwipeMenuItem(this@LinkedUserActivity).apply {
                    setText(getString(R.string.delete))
                    setBackgroundColor(getColor(R.color.red))
                    setTextColor(getColor(R.color.white))
                    width = 200
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                }
                rightMenu.addMenuItem(deleteItem)
            }
        }

        binding.rvLinkedUser.setOnItemMenuClickListener { _, position ->
            // 直接关闭菜单（使用 RecyclerView 的方法）
            binding.rvLinkedUser.smoothCloseMenu()   // 或 closeMenu()
            val user = userList[position]
            showDeleteDialog(user, position)
        }

        (binding.rvLinkedUser as RecyclerView).adapter = adapter
    }

    private fun showDeleteDialog(user: LinkedUser, position: Int) {
        val dialog = CustomDialogFragmentText()
        if (mode == MODE_SETTINGS) {
            dialog.setTitle(getString(R.string.tip))
            dialog.setMessage(getString(R.string.unlink_confirm_message))
        } else {
            dialog.setTitle(getString(R.string.tip))
            dialog.setMessage(getString(R.string.confirm_delete_user))
        }
        dialog.setShowInput(false)
        dialog.setOnConfirmListener {
            deleteDeviceUser(user, position)
        }
        dialog.show(supportFragmentManager, "DeleteDialog")
    }

    private fun deleteDeviceUser(user: LinkedUser, position: Int) {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty() || user.userId.isEmpty()) {
            Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            try {
                val request = DeleteDeviceUserRequest(
                    userId = user.userId,
                    deviceId = deviceId
                )
                val response = RetrofitNetwork.getNetworkService().deleteDeviceUser(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        userList.removeAt(position)
                        adapter.notifyItemRemoved(position)          // 通知删除动画
                        adapter.notifyItemRangeChanged(position, userList.size - position)  // 更新后续位置索引
                        Toast.makeText(this@LinkedUserActivity, "删除成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@LinkedUserActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@LinkedUserActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun initData() {
        fetchUserList()
    }

    private fun fetchUserList() {
        binding.swipeRefresh.isRefreshing = true
        lifecycleScope.launch {
            try {
                var deviceId: String? = null
                if (mode == MODE_SETTINGS) {
                    deviceId = DeviceIdEvent.getDeviceId()
                    if (deviceId.isNullOrEmpty()) {
                        Toast.makeText(this@LinkedUserActivity, "设备 ID 为空", Toast.LENGTH_SHORT).show()
                        withContext(Dispatchers.Main) {
                            binding.swipeRefresh.isRefreshing = false
                        }
                        return@launch
                    }
                }
                val response = if (mode == MODE_SETTINGS) {
                    RetrofitNetwork.getNetworkService().getDeviceUserList(deviceId!!)
                } else {
                    RetrofitNetwork.getNetworkService().getFamilyMembers()
                }
                withContext(Dispatchers.Main) {
                    binding.swipeRefresh.isRefreshing = false
                    if (response.code == 200 && response.data != null) {
                        if (mode == MODE_SETTINGS) {
                            updateDeviceUserList(response.data as List<DeviceUserBean>)
                        } else {
                            updateFamilyMembersList(response.data as List<FamilyMembersBean>)
                        }
                    } else {
                        Toast.makeText(this@LinkedUserActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    binding.swipeRefresh.isRefreshing = false
                    Toast.makeText(this@LinkedUserActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateDeviceUserList(deviceUserList: List<DeviceUserBean>) {
        fullUserList.clear()
        deviceUserList.forEach { deviceUser ->
            fullUserList.add(
                LinkedUser(
                    userId = deviceUser.userId ?: "",
                    name = deviceUser.nickName ?: "未知用户",
                    phone = deviceUser.phonenumber ?: "",
                    idCard = deviceUser.idCard ?: "",
                    time = deviceUser.createTime ?: ""
                )
            )
        }
        filterUsers(binding.etSearch.text?.toString() ?: "")
    }

    private fun updateFamilyMembersList(familyMembersList: List<FamilyMembersBean>) {
        fullUserList.clear()
        familyMembersList.forEach { member ->
            fullUserList.add(
                LinkedUser(
                    userId = member.userId ?: "",
                    name = member.nickName ?: member.parentName ?: "未知用户",
                    phone = member.phonenumber ?: "",
                    idCard = member.idCard ?: "",
                    time = member.createTime ?: ""
                )
            )
        }
        filterUsers(binding.etSearch.text?.toString() ?: "")
    }

    private fun filterUsers(keyword: String) {
        userList.clear()
        if (keyword.isEmpty()) {
            userList.addAll(fullUserList)
        } else {
            val lowerKeyword = keyword.lowercase()
            fullUserList.filter {
                it.name.lowercase().contains(lowerKeyword) ||
                it.phone.contains(keyword)
            }.forEach { userList.add(it) }
        }
        adapter.submitList(userList)
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                filterUsers(s?.toString() ?: "")
            }
        })

        binding.btnAddLinkedUser.setOnClickListener {
            if (checkUserLimit()) {
                val intent = Intent(this, AddLinkedUserActivity::class.java)
                startActivity(intent)
            }
        }

        binding.fabAdd.setOnClickListener {
            if (checkUserLimit()) {
                val intent = Intent(this, com.example.defenseapplication.personal.InvitationCodeActivity::class.java)
                startActivity(intent)
            }
        }
    }

    private fun checkUserLimit(): Boolean {
        if (fullUserList.size >= 11) {
            val dialog = CustomDialogFragmentText()
            dialog.setTitle(getString(R.string.notice))
            dialog.setMessage(getString(R.string.max_add_11_users))
            dialog.setShowInput(false)
            dialog.show(supportFragmentManager, "UserLimitDialog")
            return false
        }
        return true
    }

    private fun setupModeUI() {
        if (mode == MODE_SETTINGS) {
            binding.btnAddLinkedUser.visibility = View.VISIBLE
            binding.fabAdd.visibility = View.GONE
        } else {
            binding.btnAddLinkedUser.visibility = View.GONE
            binding.fabAdd.visibility = View.VISIBLE
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }
}
