package com.assimilate.alltrans.viewui

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
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.Logger
import com.assimilate.alltrans.common.LolAdWrapper
import com.assimilate.alltrans.common.MyTextTools
import com.assimilate.alltrans.databinding.ActivityTextResultBinding
import com.assimilate.alltrans.http.GoogleTranslator
import com.assimilate.alltrans.http.Translator
import com.assimilate.alltrans.model.LanguagesConstants
import com.assimilate.alltrans.model.PreferenceLanguageUtils
import com.assimilate.alltrans.mydb.DbTranslation
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError


class TextResultActivity : AppCompatActivity() {

    private lateinit var binding: ActivityTextResultBinding

    private var translating = false

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

    private fun initSet() {
        loadNative()
        backPressedCall()
        adLoad(MyApp.Config.text_trans_int_auto)
        adLoad(MyApp.Config.text_new_int_auto)
        adLoad(MyApp.Config.text_camera_int_auto)
        // 获取Intent
        val intent = intent
        val receivedString = intent.getStringExtra("source_text")
        binding.tvTrSource.text = receivedString
        translate(binding.tvTrSource.text.toString())

    }

    private fun loadNative() {
        LolAdWrapper.shared.loadAdShowNativeAd(
            this,
            MyApp.Config.text_trans_native_auto,
            binding.textNative,
            R.layout.ad_layout_admob_banner,
            R.layout.ad_layout_max_banner
        )
    }

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

    private fun initClick() {


        binding.ivTrBack.setOnClickListener {
            showInstAdFromCache(MyApp.Config.text_trans_int_auto)
            finish()
        }
        binding.tvTrNewTrans.setOnClickListener {

            showInstAdFromCache(MyApp.Config.text_new_int_auto)
            finish()
        }
        binding.ivReToPhoto.setOnClickListener {
            showInstAdFromCache(MyApp.Config.text_camera_int_auto)
        }
        binding.ivTrCopy.setOnClickListener {
            MyTextTools.copyToClipboard(this, binding.tvTrTarget.text.toString())
            FirebaseAnalyticsHelper.textTransCopyEvent()
        }
//        binding.ivSourceClear.setOnClickListener { finish() }
        binding.ivSourceTts.setOnClickListener {
            MyTextTools.ttsReadText(
                binding.tvTrSource.text.toString(),
                PreferenceLanguageUtils.getString("language_source"),
                this
            )
        }
        binding.ivTargetTts.setOnClickListener {
            MyTextTools.ttsReadText(
                binding.tvTrTarget.text.toString(),
                PreferenceLanguageUtils.getString("language_target"),
                this
            )
            FirebaseAnalyticsHelper.textTransPlayEvent()
        }
        binding.ivTrTargetShare.setOnClickListener {
            MyTextTools.shareText(this, binding.tvTrTarget.text.toString())
            FirebaseAnalyticsHelper.textTransShareEvent()
        }
        binding.ivTrCollect.setOnClickListener {
            val dbTranslation = DbTranslation(this)
            val isCollected = dbTranslation.toggleCollect()
            updateCollectIcon(isCollected)
            if (isCollected) {
                Toast.makeText(this, "Collection successful", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Uncollect", Toast.LENGTH_SHORT).show()
            }

            FirebaseAnalyticsHelper.textTransLikeEvent()
        }

    }

    // 更新图标状态的方法
    private fun updateCollectIcon(isCollected: Boolean) {
        if (isCollected) {
            binding.ivTrCollect.setImageResource(R.drawable.ic_like_yes) // 已收藏的图标
        } else {
            binding.ivTrCollect.setImageResource(R.drawable.ic_like_def) // 未收藏的图标
        }
    }

    private fun translate(text: String) {
        if (text.isEmpty() || translating) {
            Logger.d("log", "translating(not post data)...")
            return
        }

        translating = true

        val lanSourceCode = LanguagesConstants.getInstance().getLanguageCodeByLanguage(
            PreferenceLanguageUtils.getString("language_source"),
            MyApp.applicationContext()
        )
        val lanTargetCode = LanguagesConstants.getInstance().getLanguageCodeByLanguage(
            PreferenceLanguageUtils.getString("language_target"),
            MyApp.applicationContext()
        )

        val param = HashMap<String, String>().apply {
            put("sourceLanguage", lanSourceCode)
            put("translationLanguage", lanTargetCode)
            put("text", text)
        }

        binding.tvTrTarget.text = getString(R.string.tr_trans_ing)
        val translator: Translator<GoogleTranslator.GoogleTranslateCallback> = GoogleTranslator()
        translator.translate(param, object : GoogleTranslator.GoogleTranslateCallback {
            override fun onResponse(result: String?, errorMessage: String?) {
                translating = false
                runOnUiThread {
                    if (!TextUtils.isEmpty(result)) {
                        binding.tvTrTarget.text = result
                        MyTextTools.addToHistory(
                            this@TextResultActivity,
                            binding.tvTrSource.text.toString(),
                            result
                        )
                    } else {
                        // 处理错误信息
                        if (!TextUtils.isEmpty(errorMessage)) {
                            // 显示错误信息或记录日志
                            if (errorMessage != null) {
                                Log.e("TranslationError", errorMessage)
                            }
                        }
                        binding.tvTrTarget.text = getString(R.string.tr_trans_fail)
                    }
                }
            }

            override fun onFailure(errorMessage: String?) {
                translating = false
                FirebaseAnalyticsHelper.textTransResultEvent(
                    MyApp.Config.FAIL_REASON,
                    "failed: $errorMessage"
                )
                runOnUiThread {
                    // 显示失败信息或记录日志
                    if (!TextUtils.isEmpty(errorMessage)) {
                        if (errorMessage != null) {
                            Log.e("TranslationFailure", errorMessage)
                        }
                        binding.tvTrTarget.text = getString(R.string.tr_trans_fail)
                    } else {
                        binding.tvTrTarget.text = getString(R.string.tr_trans_fail)
                    }
                }
            }
        })

    }

    private fun doBack() {
        finish()
    }

    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@TextResultActivity,
            place,
            object : LolAdWrapper.LolShowListener {
                override fun shown() {
                    // 处理广告展示成功
                }

                override fun showFailed(error: LolShowError?) {
                    // 处理广告展示失败
                    if (place == MyApp.Config.text_camera_int_auto) {
                        startActivity(
                            Intent(
                                this@TextResultActivity,
                                PhotoImageActivity::class.java
                            ).putExtra(
                                "key_start_ph",
                                "text"
                            )
                        )
                    } else {
                        doBack()
                    }

                }

                override fun closed() {
                    // 处理广告关闭
                    if (place == MyApp.Config.text_camera_int_auto) {
                        startActivity(
                            Intent(
                                this@TextResultActivity,
                                PhotoImageActivity::class.java
                            ).putExtra(
                                "key_start_ph",
                                "text"
                            )
                        )
                    } else {
                        doBack()
                    }

                }
            })
    }


}