package com.base.browserwhite.ui.activity.search

import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.searchEngineSp
import com.base.browserwhite.databinding.ActivitySearchBinding
import com.base.browserwhite.help.SearchTipUtils.getSearchTip
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.utils.BarUtils.getStatusBarHeight
import com.base.browserwhite.utils.BarUtils.setStatusBarColor
import com.base.browserwhite.utils.BarUtils.setStatusBarLightMode
import com.base.browserwhite.utils.LinkSearchUtils


class SearchActivity : BaseActivity<ActivitySearchBinding>() {

    private lateinit var searchAdapter: SearchAdapter

    override val binding: ActivitySearchBinding by lazy {
        ActivitySearchBinding.inflate(layoutInflater)
    }


    override fun initView() {
        setStatusBarLightMode(this, true)
        setStatusBarColor(this, Color.TRANSPARENT)

        val layout = binding.clTop
        val layoutParams = layout.layoutParams as LinearLayout.LayoutParams
        val finalPosition = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16f, getResources().displayMetrics).toInt()
//        layoutParams.topMargin = getStatusBarHeight() + finalPosition
        layoutParams.topMargin = finalPosition
        layout.setLayoutParams(layoutParams)
        layout.visibility = View.VISIBLE

        switchSearch(searchEngineSp)

        searchAdapter = SearchAdapter()
        searchAdapter.searchAction = { content ->
            startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                putExtra("url", LinkSearchUtils.getSpSearchAction(content))
            })
        }
        binding.rv.adapter = searchAdapter


    }

    fun aaa() {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager

        // 显示软键盘
        imm.showSoftInput(binding.editWeb, InputMethodManager.SHOW_IMPLICIT)

        // 隐藏软键盘
//        imm.hideSoftInputFromWindow(binding.editWeb.windowToken, 0)
    }

    override fun initListener() {
        super.initListener()

        binding.editWeb.addTextChangedListener {

            if (it.isNullOrEmpty()) {
                binding.llFastInput2.visibility = View.GONE
                binding.llFastInput1.visibility = View.VISIBLE
                return@addTextChangedListener
            }
            binding.flSearch.isVisible = it.toString().isNotEmpty()
            searchAdapter.submitList(listOf())
            querySearchTip(it.toString())
        }

        binding.editWeb.setOnClickListener {
//            aaa()
            binding.editWeb.selectAll()
        }
        binding.ivClear.setOnClickListener {
            binding.editWeb.setText("")
            binding.flSearch.visibility = View.GONE
            searchAdapter.submitList(listOf())
        }
        binding.tvSearch.setOnClickListener {
            val content = binding.editWeb.text.toString()
            startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                putExtra("url", LinkSearchUtils.getSpSearchAction(content))
            })
        }

        arrayOf(binding.tvWww, binding.tvM, binding.tvWap, binding.tvDian, binding.tvXieGang).forEach {
            it.setOnClickListener { textView ->
                binding.editWeb.append((textView as TextView).text)
                binding.llFastInput1.visibility = View.GONE
                binding.llFastInput2.visibility = View.VISIBLE
            }
        }
        arrayOf(binding.tvDian2, binding.tvXieGang2, binding.tvCom, binding.tvNet, binding.tvOrg, binding.tvCn).forEach {
            it.setOnClickListener { textView ->
                binding.editWeb.append((textView as TextView).text)
            }
        }
    }

    private fun querySearchTip(query: String) {
        Thread {
            val list = getSearchTip(query)
            Handler(mainLooper).post {
                if (list != null) {
                    searchAdapter.submitList(list)
                } else {
                    searchAdapter.submitList(listOf())
                }
            }
        }.start()
    }

    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        finish()
        setResult(10086)
        overridePendingTransition(0, 0)
    }

    companion object {
        fun startActivityWithButtonAnimation(currentActivity: Activity, button: View, verticalOffset: Int) {
            val finalPosition =
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16f, currentActivity.resources.displayMetrics).toInt()
            val buttonTop = button.top - finalPosition
            val distanceToTop = -buttonTop - verticalOffset
            val animator = ObjectAnimator.ofFloat(button, "translationY", button.translationY, distanceToTop.toFloat())
            animator.setDuration(500)
            animator.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {}
                override fun onAnimationEnd(animation: Animator) {
                    button.visibility = View.VISIBLE
                    val intent = Intent(currentActivity, SearchActivity::class.java)
                    currentActivity.startActivityForResult(intent, 10086)
                    currentActivity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }

                override fun onAnimationCancel(animation: Animator) {}
                override fun onAnimationRepeat(animation: Animator) {}
            })
            animator.start()
        }
    }

    private fun switchSearch(website: String) {
        searchEngineSp = website
        when (website) {
            ConstObject.GOOGLE -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
            }

            ConstObject.BING -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
            }

            ConstObject.YAHOO -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
            }

            ConstObject.DUCKDUCKGO -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
            }

            ConstObject.YANDEX -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
            }

            ConstObject.BAIDU -> {
                binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
            }

        }

    }
}
