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.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
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.bean.SearchRecordBean
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.setStatusBarColor
import com.base.browserwhite.utils.BarUtils.setStatusBarLightMode
import com.base.browserwhite.utils.LinkSearchUtils
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.SEARCH_RECORD_SP_KEY
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.android.material.chip.Chip
import com.google.gson.Gson


class SearchActivity : BaseActivity<ActivitySearchBinding>() {

    private lateinit var searchAdapter: SearchAdapter
    private lateinit var searchRecordAdapter: SearchRecordAdapter


    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

        searchRecordAdapter = SearchRecordAdapter()
        val layoutManager = FlexboxLayoutManager(this)
        // 设置主轴排列方向
        layoutManager.flexDirection = FlexDirection.ROW
        // 设置换行方式
        layoutManager.flexWrap = FlexWrap.WRAP
        // 设置水平对齐方式
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvFlow.layoutManager = layoutManager
        binding.rvFlow.adapter = searchAdapter

        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.chipGroup.visibility = View.GONE
            binding.tvCancel.visibility = View.GONE
            binding.ivClear.visibility = View.VISIBLE
            binding.tvSearch.visibility = View.VISIBLE

            searchAdapter.submitList(listOf())
            querySearchTip(it.toString())
        }

        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()
            SpBeanUtils.addSpBean(SEARCH_RECORD_SP_KEY, SearchRecordBean(content))
            startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                putExtra("url", LinkSearchUtils.getSpSearchAction(content))
                addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
            })
            finish()
        }

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

//        binding.chipGroup.setOnCheckedStateChangeListener { chipGroup, ints ->
//            val id = ints[0]
//            if (id == -1) {
//
//            } else {
//                val bean = searchRecordList.find { it.id == id.toLong() }
//                if (bean != null) {
//                    startActivity(Intent(this, WebBrowserActivity::class.java).apply {
//                        putExtra("url", LinkSearchUtils.getSpSearchAction(bean.content))
//                        addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
//                    })
//                    chipGroup.isClickable = false
//                }
//            }
//
//        }
    }

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


        fun startActivityWithButtonExpandAnimation(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, "scaleX", 1f, 1.05f)
//            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)
            }

        }

    }


    private val searchRecordList = arrayListOf<SearchRecordBean>()
    private fun showSearchRecord() {
        binding.chipGroup.visibility = View.VISIBLE
        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)
        }
        searchRecordList.addAll(list)
        searchRecordAdapter.submitList(searchRecordList)


        list.forEach {
            val chip = Chip(this)
            chip.id = it.id.toInt()
            chip.text = it.content
            chip.setTextColor(Color.BLACK)
            chip.textSize = 14f
            chip.background = ContextCompat.getDrawable(this, R.drawable.bg_eef1f6_20)
            chip.isCheckable = true
            chip.isCheckedIconVisible = false
            chip.height = this.resources.getDimensionPixelOffset(R.dimen.dp_40)
            binding.chipGroup.addView(chip)

        }


        val deleteChip = Chip(this)
        deleteChip.id = -1
        deleteChip.text = ""
        deleteChip.isCheckable = true
        deleteChip.isCheckedIconVisible = false
        deleteChip.isChipIconVisible = true
        deleteChip.chipIcon = ContextCompat.getDrawable(this, R.mipmap.del_chip)
        deleteChip.gravity = Gravity.CENTER
        deleteChip.setChipIconSizeResource(R.dimen.dp_20)
        deleteChip.iconStartPadding = this.resources.getDimension(R.dimen.dp_15)
        deleteChip.height = this.resources.getDimensionPixelOffset(R.dimen.dp_40)
        deleteChip.width = this.resources.getDimensionPixelOffset(R.dimen.dp_40)


        binding.chipGroup.addView(deleteChip)
    }
}
