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

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.os.Handler
import android.util.DisplayMetrics
import android.util.Log
import android.util.TypedValue
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.base.browserwhite.MyApplication
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.searchEngineSp
import com.base.browserwhite.bean.SearchRecordBean
import com.base.browserwhite.databinding.ActivitySearchBinding
import com.base.browserwhite.help.Constants
import com.base.browserwhite.help.Constants.CHANGE_SEARCH_URL
import com.base.browserwhite.help.RxBus
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.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.utils.BarUtils.setStatusBarColor
import com.base.browserwhite.utils.BarUtils.setStatusBarLightMode
import com.base.browserwhite.utils.LinkSearchUtils
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.SEARCH_RECORD_SP_KEY
import com.base.browserwhite.utils.Utils
import com.base.browserwhite.utils.Utils.dpToPx
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.gson.Gson


class SearchActivity : BaseActivity<ActivitySearchBinding>() {

    private val TAG = "SearchActivity"
    private lateinit var searchAdapter: SearchAdapter
    private lateinit var searchRecordAdapter: SearchRecordAdapter
    private var isHomeSearch: Boolean = true

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

    private fun searchJump(content: String) {
        var link = ""
        LinkSearchUtils.handleInput(content, loadUrl = {
            link = it
        }, performSearch = {
            link = LinkSearchUtils.getSpSearchAction(content)
        })
        SpBeanUtils.addSpBean(SEARCH_RECORD_SP_KEY, SearchRecordBean(content))

        LogEx.logDebug(TAG, "isHomeSearch=$isHomeSearch")
        if (isHomeSearch) {
            startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                putExtra("url", link)
                putExtra("action", "search")
                addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
            })
        } else {
            RxBus.get().post(CHANGE_SEARCH_URL, link)
            setResult(10087)
        }
        RxBus.get().post(Constants.RESET_SEARCH_VIEW, 1)
        finish()
        overridePendingTransition(0, 0)
    }

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

        isHomeSearch = intent.extras?.getBoolean("isHomeSearch") ?: true

        switchSearch(searchEngineSp)

        searchAdapter = SearchAdapter()
        searchAdapter.searchAction = { content ->
            searchJump(content)
        }
        binding.rv.adapter = searchAdapter

        searchRecordAdapter = SearchRecordAdapter()
        searchRecordAdapter.jumpAction = { content ->
            searchJump(content)
        }
        searchRecordAdapter.deleteAction = {
            showDeleteTipDialog(desc = "Clear all search records?") {
                SpBeanUtils.clearSpBean(SEARCH_RECORD_SP_KEY)
                showSearchRecord()
            }
        }
        val layoutManager = FlexboxLayoutManager(this)
        // 设置主轴排列方向
        layoutManager.flexDirection = FlexDirection.ROW
        // 设置换行方式
        layoutManager.flexWrap = FlexWrap.WRAP
        // 设置水平对齐方式
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvFlow.layoutManager = layoutManager
        binding.rvFlow.adapter = searchRecordAdapter

        showSearchRecord()
    }

    override fun initListener() {
        super.initListener()

        binding.editWeb.addTextChangedListener {

            if (it.isNullOrEmpty()) {
                binding.llFastInput2.visibility = View.GONE
                binding.llFastInput1.visibility = View.VISIBLE
                binding.tvCancel.visibility = View.VISIBLE
                binding.ivClear.visibility = View.GONE
                binding.tvSearch.visibility = View.GONE
                showSearchRecord()
                return@addTextChangedListener
            }
            binding.rv.visibility = View.VISIBLE
            binding.tvCancel.visibility = View.GONE
            binding.rvFlow.visibility = View.GONE
            binding.ivClear.visibility = View.VISIBLE
            binding.tvSearch.visibility = View.VISIBLE

            searchAdapter.submitList(listOf())
            querySearchTip(it.toString())
        }
        binding.editWeb.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {

            }
        }
        binding.editWeb.setOnEditorActionListener { v, actionId, event ->

            if (actionId == EditorInfo.IME_ACTION_DONE || (event.keyCode == KeyEvent.KEYCODE_ENTER)) {
                val content = binding.editWeb.text.toString()
                if (content.isNotEmpty()) {
                    searchJump(content)
                }
            }

            // 返回 true 表示你已经处理了这个事件
            true
        }
        if (searchContent.isNotEmpty()) {
            binding.editWeb.setText(searchContent)
            binding.tvCancel.visibility = View.GONE
            binding.tvSearch.visibility = View.VISIBLE
            binding.ivClear.visibility = View.VISIBLE
            searchContent = ""
        }

        binding.editWeb.requestFocus()
        binding.root.postDelayed({
            binding.editWeb.requestFocus()
            binding.editWeb.selectAll()

            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(binding.editWeb, InputMethodManager.SHOW_IMPLICIT)
        }, 500)


        binding.editWeb.setOnClickListener {
            binding.editWeb.selectAll()
        }
        binding.ivClear.setOnClickListener {
            binding.editWeb.setText("")
            searchAdapter.submitList(listOf())
            binding.ivClear.visibility = View.GONE
            binding.tvSearch.visibility = View.GONE
            binding.tvCancel.visibility = View.VISIBLE
        }
        binding.tvSearch.setOnClickListener {
            val content = binding.editWeb.text.toString()
            if (content.isNotEmpty()) {
                searchJump(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)
            }
        }
        binding.tvCancel.setOnClickListener {
            onBackPressed()
        }
    }

    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 {

        var searchContent: String = ""

        fun startActivityWithButtonAnimation(currentActivity: Activity, button: View, verticalOffset: Int) {
            val finalPosition =MyApplication.context.dpToPx(16f)
            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).apply {
                        putExtra("isHomeSearch", true)
                    }
                    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()
        }


        fun startActivityWithButtonExpandAnimation(
            currentActivity: Activity,
            button: View,
            verticalOffset: Int
        ) {
            val marginEnd = MyApplication.context.dpToPx(30f)
            val screenWidth =Utils.getScreenWidth(MyApplication.context) - marginEnd
            val x = screenWidth.toFloat() / button.width.toFloat()
            val scaleXAnimator = ObjectAnimator.ofFloat(button, "scaleX", 1f, x)
            val scaleYAnimator = ObjectAnimator.ofFloat(button, "scaleY", 1f, 50f / 44f)
            button.pivotX = 0f
            button.pivotY = 0f

            scaleXAnimator.setDuration(500)
            scaleYAnimator.setDuration(500)


            val animatorSet = AnimatorSet()
            animatorSet.playTogether(
                scaleXAnimator,
                scaleYAnimator
            )

            animatorSet.start()
            animatorSet.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {
                }

                override fun onAnimationEnd(animation: Animator) {
                    val intent = Intent(currentActivity, SearchActivity::class.java).apply {
                        putExtra("isHomeSearch", false)
                    }
                    currentActivity.startActivityForResult(intent, 10087)
                    currentActivity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }

                override fun onAnimationCancel(animation: Animator) {
                }

                override fun onAnimationRepeat(animation: Animator) {
                }
            })
        }
    }

    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)
            }

        }

    }


    private val searchRecordList = arrayListOf<SearchRecordBean>()
    private fun showSearchRecord() {
        binding.rv.visibility = View.GONE
        binding.rvFlow.visibility = View.VISIBLE

        searchRecordList.clear()
        val gson = Gson()
        val list = SpBeanUtils.getSpBeanList(SEARCH_RECORD_SP_KEY).map {
            gson.fromJson(it, SearchRecordBean::class.java)
        }.reversed()

        val lastList = if (list.size >= 4) list.subList(0, 4) else list

        searchRecordList.addAll(lastList)
        searchRecordAdapter.submitList(searchRecordList)
        if (list.isNotEmpty()) {
            searchRecordAdapter.add(SearchRecordBean().apply { isDelete = true })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}
