package com.example.defenseapplication.liveVideo

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
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.databinding.LinkedUserActivityBinding
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.gyf.immersionbar.ImmersionBar
//关联用户页面
class LinkedUserActivity : AppCompatActivity() {

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

    companion object {
        const val REQUEST_CODE_SEARCH = 1001
        const val EXTRA_SEARCH_RESULT = "search_result"
        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()
    }

    private fun initView() {
        val deleteText = if (mode == MODE_SETTINGS) getString(R.string.unlink) else getString(R.string.delete)
        adapter = LinkedUserAdapter(
            deleteText = deleteText,
            onItemClick = { user, position ->
                val intent = Intent(this, UserDetailsActivity::class.java).apply {
                    putExtra("name", user.name)
                    putExtra("phone", user.phone)
                    putExtra("idCard", user.idCard)
                    putExtra("time", user.time)
                }
                startActivity(intent)
            },
            onDeleteClick = { user, position ->
                showUnlinkDialog(user, position)
            }
        )
        binding.rvLinkedUser.layoutManager = LinearLayoutManager(this)
        binding.rvLinkedUser.adapter = adapter

        val swipeThreshold = -300f
        val heldPositions = mutableMapOf<Int, Boolean>()

        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean = false

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            }

            override fun onChildDraw(
                c: android.graphics.Canvas,
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                dX: Float,
                dY: Float,
                actionState: Int,
                isCurrentlyActive: Boolean
            ) {
                if (viewHolder is LinkedUserAdapter.LinkedUserViewHolder) {
                    val contentLayout = viewHolder.getContentLayout()
                    val position = viewHolder.adapterPosition

                    if (isCurrentlyActive) {
                        val swipeDistance = if (dX < swipeThreshold) swipeThreshold else dX
                        contentLayout.translationX = swipeDistance
                    } else {
                        val isHeld = heldPositions[position]
                        if (isHeld == true) {
                            contentLayout.translationX = swipeThreshold
                        }
                    }
                }
            }

            /*
            - 滑动超过一半后松手：列表项 保持在滑动位置 ，显示"解除关联"按钮
            - 滑动未超过一半松手：列表项 恢复原位
            * */
            override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
                super.clearView(recyclerView, viewHolder)
                if (viewHolder is LinkedUserAdapter.LinkedUserViewHolder) {
                    val position = viewHolder.adapterPosition
                    val contentLayout = viewHolder.getContentLayout()

                    if (contentLayout.translationX < swipeThreshold / 2) {
                        heldPositions[position] = true
                        contentLayout.translationX = swipeThreshold
                    } else {
                        heldPositions.remove(position)
                        contentLayout.animate()
                            .translationX(0f)
                            .setDuration(300)
                            .start()
                    }
                }
            }

            override fun getSwipeThreshold(viewHolder: RecyclerView.ViewHolder): Float = 0.05f
        })
        itemTouchHelper.attachToRecyclerView(binding.rvLinkedUser)
    }

    private var currentSwipePosition: Int = -1
    private var currentSwipeHeld: Boolean = false

    private fun showUnlinkDialog(user: LinkedUser, position: Int) {
        currentSwipePosition = position
        currentSwipeHeld = true

        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.setPositiveText(getString(R.string.confirm))
        dialog.setNegativeText(getString(R.string.cancel))
        dialog.setOnConfirmListener {
            userList.removeAt(position)
            adapter.removeItem(position)
            resetSwipeState()
        }
        dialog.setOnDismissListener {
            resetSwipeState()
        }
        dialog.show(supportFragmentManager, "UnlinkDialog")
    }

    private fun resetSwipeState() {
        if (currentSwipePosition >= 0 && currentSwipeHeld) {
            binding.rvLinkedUser.post {
                val viewHolder = binding.rvLinkedUser.findViewHolderForAdapterPosition(currentSwipePosition)
                if (viewHolder is LinkedUserAdapter.LinkedUserViewHolder) {
                    viewHolder.getContentLayout().animate()
                        .translationX(0f)
                        .setDuration(300)
                        .start()
                }
                currentSwipePosition = -1
                currentSwipeHeld = false
            }
        }
    }

    private fun initData() {
        userList.clear()
        userList.add(LinkedUser("张三", "12388888888", "123456789012345678", "2026-05-06 16:03:26"))
        userList.add(LinkedUser("李四", "13899999999", "987654321098765432", "2026-05-05 14:20:15"))
        userList.add(LinkedUser("王五", "15977777777", "456123789012345678", "2026-05-04 10:15:30"))
        adapter.submitList(userList)
    }

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

        binding.searchLayout.setOnClickListener {
            val intent = Intent(this, LinkedUserSearchActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_SEARCH)
        }

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

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

    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)
        if (requestCode == REQUEST_CODE_SEARCH && resultCode == RESULT_OK) {
            data?.getStringExtra(EXTRA_SEARCH_RESULT)?.let { result ->
                val newUser = LinkedUser(
                    name = result,
                    phone = "13800000000",
                    idCard = "110101199001011234",
                    time = "2026-05-10 ${android.text.format.DateFormat.format("HH:mm:ss", System.currentTimeMillis())}"
                )
                userList.add(0, newUser)
                adapter.submitList(userList)
            }
        }
    }
}