package com.kaixed.kchat.view.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.bumptech.glide.Glide
import com.kaixed.kchat.databinding.ActivitySearchFriendsBinding
import com.kaixed.kchat.databinding.DialogLoadingBinding
import com.kaixed.kchat.model.search.User
import com.kaixed.kchat.viewmodel.SearchFriendsViewModel


class SearchFriendsActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySearchFriendsBinding
    private var isSearching = false
    private lateinit var userItem: User
    private lateinit var loadingDialog: Dialog

    private val searchFriendsViewModel: SearchFriendsViewModel by viewModels()

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

        initView()

        setOnClick()

    }

    private fun setOnClick() {
        binding.clFriends.setOnClickListener {
            val intent = Intent(this, ApplyFriendsDetailActivity::class.java)
            intent.putExtra("user", userItem)
            startActivity(intent)
        }
    }

    private fun initView() {
        binding.clFriends.visibility = View.GONE
        binding.tvTitle.visibility = View.GONE

        binding.etSearch.requestFocus()
        binding.etSearch.addTextChangedListener(afterTextChanged = {
            it?.let {
                if (it.isEmpty()) {
                    binding.clFriends.visibility = View.GONE
                    binding.tvTitle.visibility = View.GONE
                    binding.clSearchUser.visibility = View.GONE
                } else {
                    binding.clSearchUser.visibility = View.VISIBLE

                    val spannableString = SpannableString("搜索：$it")
                    val colorSpan = ForegroundColorSpan(Color.parseColor("#2BA245"))

                    spannableString.setSpan(
                        colorSpan,
                        3,
                        it.length + 3,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    binding.tvSearchContent.text = spannableString
                }
                isSearching = it.isNotEmpty()
            }
        })

        binding.etSearch.postDelayed({
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(binding.etSearch, InputMethodManager.SHOW_IMPLICIT)
        }, 200)

        binding.clSearchUser.setOnClickListener {
            loadingDialog = showLoadingDialog(this)

            val username = binding.etSearch.text.toString()
            searchFriendsViewModel.searchFriends(username)?.observe(this) { value ->
                loadingDialog.dismiss()
                if (value != null) {
                    userItem = value.data
                    if (::userItem.isInitialized) {
                        setVisibility(true)
                        setContent()
                    }
                }
            }
        }

        binding.tvCancel.setOnClickListener {
            finish()
        }
    }

    private fun showLoadingDialog(context: Context): Dialog {
        val binding = DialogLoadingBinding.inflate(LayoutInflater.from(context))
        val dialog = Dialog(context)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(false)
        dialog.setContentView(binding.root)
        dialog.show()
        return dialog
    }

    private fun setContent() {
        binding.tvNickname.text = userItem.nickname
        binding.tvSignature.text = userItem.signature
        Glide.with(this).load(userItem.avatarUrl).into(binding.ivAvatar)
    }

    private fun setVisibility(isSearchClick: Boolean) {
        binding.clFriends.visibility = if (isSearchClick) View.VISIBLE else View.GONE
        binding.tvTitle.visibility = if (isSearchClick) View.VISIBLE else View.GONE
        binding.clSearchUser.visibility = if (isSearchClick) View.GONE else View.VISIBLE
    }
}