package com.example.defenseapplication.liveVideo

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.defenseapplication.R
import com.example.defenseapplication.adapter.AddLinkedUserAdapter
import com.example.defenseapplication.adapter.UserItem
import com.example.defenseapplication.bean.AddDeviceUserRequest
import com.example.defenseapplication.bean.FamilyMembersBean
import com.example.defenseapplication.databinding.AddLinkedUserActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.DeviceUserUpdateEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import androidx.recyclerview.widget.RecyclerView
//添加关联用户
class AddLinkedUserActivity : AppCompatActivity() {
    private lateinit var binding: AddLinkedUserActivityBinding
    private val selectedPhoneSet = mutableSetOf<String>()
    private val fullUserItemList = mutableListOf<UserItem>()
    private val userItemList = mutableListOf<UserItem>()
    private val selectedUserIdMap = mutableMapOf<String, String>()

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

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

        initRecyclerView()
        initListener()
        setupSwipeRefresh()
        fetchFamilyMembers()
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefresh.setOnRefreshListener {
            fetchFamilyMembers()
        }
    }

    private fun initRecyclerView() {
        binding.rvAddLinkedUser.layoutManager = LinearLayoutManager(this)
        binding.rvAddLinkedUser.adapter =
            AddLinkedUserAdapter(userItemList, selectedPhoneSet, selectedUserIdMap) { phone, isChecked, userId ->
                if (isChecked) {
                    selectedPhoneSet.add(phone)
                    userId?.let { selectedUserIdMap[phone] = it }
                } else {
                    selectedPhoneSet.remove(phone)
                    selectedUserIdMap.remove(phone)
                }
            }

        // 设置上拉加载更多
        binding.rvAddLinkedUser.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                if (totalItemCount > 0 && lastVisibleItem >= totalItemCount - 3) {
                    // 滑到底部时自动刷新（加载更多）
                    if (!binding.swipeRefresh.isRefreshing) {
                        fetchFamilyMembers()
                    }
                }
            }
        })
    }

    private fun fetchFamilyMembers() {
        binding.swipeRefresh.isRefreshing = true
        lifecycleScope.launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getFamilyMembers()
                withContext(Dispatchers.Main) {
                    binding.swipeRefresh.isRefreshing = false
                    if (response.code == 200) {
                        if (response.data != null && response.data.isNotEmpty()) {
                            updateFamilyMemberList(response.data)
                        } else {
                            Toast.makeText(this@AddLinkedUserActivity, "暂无家庭成员数据", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        Toast.makeText(this@AddLinkedUserActivity, "请求失败: ${response.msg}", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("AddLinkedUserActivity", "网络请求异常", e)
                withContext(Dispatchers.Main) {
                    binding.swipeRefresh.isRefreshing = false
                    Toast.makeText(this@AddLinkedUserActivity, "网络请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

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

    private fun filterUsers(keyword: String) {
        userItemList.clear()
        if (keyword.isEmpty()) {
            userItemList.addAll(fullUserItemList)
        } else {
            val lowerKeyword = keyword.lowercase()
            fullUserItemList.filter {
                it.name.lowercase().contains(lowerKeyword) ||
                it.phone.contains(keyword)
            }.forEach { userItemList.add(it) }
        }
        binding.rvAddLinkedUser.adapter?.notifyDataSetChanged()
    }

    private fun initListener() {
        binding.btnAddLinkedUser.setOnClickListener {
            if (selectedPhoneSet.isEmpty()) {
                Toast.makeText(this, getString(R.string.please_select_at_least_one_user), Toast.LENGTH_SHORT).show()
            } else {
                addDeviceUser()
            }
        }
        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() ?: "")
            }
        })
    }

    private fun addDeviceUser() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            var successCount = 0
            for ((phone, userId) in selectedUserIdMap) {
                try {
                    val request = AddDeviceUserRequest(
                        deviceId = deviceId,
                        userId = userId
                    )
                    val response = RetrofitNetwork.getNetworkService().addDeviceUser(request)
                    withContext(Dispatchers.Main) {
                        if (response.code == 200) {
                            successCount++
                        } else {
                            Toast.makeText(this@AddLinkedUserActivity, "添加用户 $phone 失败: ${response.msg}", Toast.LENGTH_SHORT).show()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@AddLinkedUserActivity, "添加用户 $phone 失败: 网络错误", Toast.LENGTH_SHORT).show()
                    }
                }
            }

            withContext(Dispatchers.Main) {
                if (successCount > 0) {
                    Toast.makeText(this@AddLinkedUserActivity, "成功添加 $successCount 个用户", Toast.LENGTH_SHORT).show()
                    DeviceUserUpdateEvent.notifyUpdate()
                    finish()
                }
            }
        }
    }
}