package com.assimilate.alltrans.viewui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.R
import com.assimilate.alltrans.common.FirebaseAnalyticsHelper
import com.assimilate.alltrans.common.LolAdWrapper
import com.assimilate.alltrans.databinding.ActivityDicBinding
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError
import java.util.Locale

class DicActivity : AppCompatActivity() {

    private lateinit var binding: ActivityDicBinding
    private var isWikiIng = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDicBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.dic_root)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化ProgressBar
        binding.wikiProgressBar.visibility = View.GONE
        adLoad(MyApp.Config.directory_int_auto)

        intiClick()
        backPressedCall()

    }

    private fun intiClick() {
        binding.ivDicMore.setOnClickListener {
            // 创建 PopupMenu
            val popupMenu = PopupMenu(this, it)
            // 关联菜单资源文件
            popupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)
            // 设置菜单项点击事件
            popupMenu.setOnMenuItemClickListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.action_one -> {

                        if (binding.editTextWord.text.toString().isNotEmpty()) {
                            val url = generateWiktionaryUrl(binding.editTextWord.text.toString())
                            // 创建Intent
                            val intent = Intent(Intent.ACTION_VIEW).apply {
                                data = Uri.parse(url)
                            }

                            // 启动浏览器
                            startActivity(intent)
                        } else {
                            Toast.makeText(this, R.string.dic_et, Toast.LENGTH_SHORT).show()
                        }

                        // 处理第一个菜单项的点击事件
                        true
                    }

                    else -> false
                }
            }

            // 显示 PopupMenu
            popupMenu.show()
        }

        binding.editTextWord.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // 隐藏键盘
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(binding.editTextWord.windowToken, 0)
                true
            } else {
                false
            }
        }

        binding.ivDicBack.setOnClickListener {
            showInstAdFromCache(MyApp.Config.directory_int_auto)
            finish()
        }
        binding.buttonSearch.setOnClickListener {
            val word = binding.editTextWord.text.toString().trim()
            if (word.isNotEmpty()) {
                if (!isWikiIng) {
                    getWeb(word)
                } else {
                    Toast.makeText(this, R.string.dic_wikiing, Toast.LENGTH_SHORT).show()
                }

            } else {
                Toast.makeText(this, R.string.dic_et, Toast.LENGTH_SHORT).show()
            }
            FirebaseAnalyticsHelper.directoryTransClickEvent()
        }
    }


    private fun backPressedCall() {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showInstAdFromCache(MyApp.Config.directory_int_auto)
                finish()
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)
    }

    private fun getWeb(word: String) {
        // 显示 ProgressBar
        binding.wikiProgressBar.visibility = View.VISIBLE
        isWikiIng = true
        // 创建 WebView 实例并配置
        val webView = createConfiguredWebView()

        // 设置 WebView 浏览器客户端
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                // 注入 JavaScript 隐藏指定区域
                injectJavaScript(view)
                // 加载完成后隐藏 ProgressBar
                binding.wikiProgressBar.visibility = View.GONE
                isWikiIng = false

            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                // 加载失败后隐藏 ProgressBar
                binding.wikiProgressBar.visibility = View.GONE
                isWikiIng = false
                FirebaseAnalyticsHelper.directoryTransResultEvent(
                    MyApp.Config.FAIL_REASON,
                    error.toString()
                )
            }
        }

        webView.webChromeClient = WebChromeClient()

        // 设置 WebView 布局参数并添加到视图中
        val params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        webView.layoutParams = params
        binding.toUrl.addView(webView)
        // 加载指定的 URL
        webView.loadUrl(generateWiktionaryUrl(word))
    }

    // 创建并配置 WebView
    private fun createConfiguredWebView(): WebView {
        val webView = WebView(this)
        val settings = webView.settings

        settings.loadsImagesAutomatically = true
        settings.javaScriptEnabled = true
        settings.domStorageEnabled = true
        WebView.setWebContentsDebuggingEnabled(false)

        return webView
    }

    // 注入 JavaScript 脚本隐藏指定区域
    private fun injectJavaScript(view: WebView?) {
        view?.loadUrl(
            """
         javascript:(function() {
                  
            var mainTitle = document.getElementById('firstHeading');
            if (mainTitle) {
                mainTitle.style.color = 'rgb(16, 171, 251)';
                mainTitle.style.fontWeight = 'bold';
                mainTitle.style.fontSize = '43px';
            }
            
            var bodyContent = document.getElementById('bodyContent');
            if (bodyContent) {
                bodyContent.style.marginBottom = '55px'; 
            }
            
            var header = document.getElementsByClassName('minerva-header');
            if (header.length > 0) {
                header[0].style.display = 'none';
            }

            var footer = document.getElementsByClassName('post-content footer-content');
            if (footer.length > 0) {
                footer[0].style.display = 'none';
            }
         
            var minerva_footer = document.getElementsByClassName('mw-footer minerva-footer');
            if (minerva_footer.length > 0) {
                minerva_footer[0].style.display = 'none';
            }
            
              var last_modified_bar = document.getElementsByClassName('post-content last-modified-bar__content');
            if (last_modified_bar.length > 0) {
                last_modified_bar[0].style.display = 'none';
            }
        
            var actionsMenu = document.getElementsByClassName('page-actions-menu');
            if (actionsMenu.length > 0) {
                actionsMenu[0].style.display = 'none';
            }

            var editSections = document.getElementsByClassName('mw-editsection');
            for (var i = 0; i < editSections.length; i++) {
                editSections[i].style.display = 'none';
            }
        })();
        """.trimIndent()
        )
    }

    private fun generateWiktionaryUrl(word: String?): String {
        // 检查传入的字符串是否为空或null
        if (word.isNullOrBlank()) {
            throw IllegalArgumentException("Word cannot be null or blank")
        }

        val language = try {
            // 获取本地语言，若获取失败则抛出异常
            Locale.getDefault().language
        } catch (e: Exception) {
            throw RuntimeException("Unable to retrieve the default language", e)
        }

        val lowerCaseWord = try {
            // 将传入字符串转换为小写，若转换失败则抛出异常
            word.lowercase(Locale.ROOT)
        } catch (e: Exception) {
            throw RuntimeException("Unable to convert word to lowercase", e)
        }

        return "https://$language.m.wiktionary.org/wiki/$lowerCaseWord"
    }


    private fun adLoad(place: String) {
        // 加载广告
        LolAdWrapper.shared.loadAdIfNotCached(
            this,
            place,
            object : LolAdWrapper.LoLLoadListener {
                override fun loadFailed(error: LolLoadError?) {
                }

                override fun loaded() {
                    // 处理加载成功
                }
            })

    }

    private fun showInstAdFromCache(place: String) {
        // 如果需要立刻展示广告，可以调用展示方法
        LolAdWrapper.shared.showAdIfCached(
            this,
            place,
            object : LolAdWrapper.LolShowListener {
                override fun shown() {
                    // 处理广告展示成功
                }

                override fun showFailed(error: LolShowError?) {
                    // 处理广告展示失败
                    finish()
                }

                override fun closed() {
                    // 处理广告关闭
                    finish()
                }
            })
    }


}
