package com.assimilate.alltrans.viewui


import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
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.keepmodel.LanguagesConstants
import com.assimilate.alltrans.common.Logger
import com.assimilate.alltrans.keepmodel.PreferenceLanguageUtils
import com.assimilate.alltrans.common.Widget
import com.assimilate.alltrans.databinding.ActivityTextResultBinding
import com.assimilate.alltrans.http.GoogleTranslator
import com.assimilate.alltrans.http.Translator
import com.assimilate.alltrans.mydb.DbTranslation
import com.assimilate.alltrans.mydb.Translations
import java.util.Locale


class TextResultActivity : AppCompatActivity() {

    private lateinit var binding: ActivityTextResultBinding
    private lateinit var tts: TextToSpeech
    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() {
        // 获取Intent
        val intent = intent
        val receivedString = intent.getStringExtra("source_text")
        binding.tvTrSource.text = receivedString
        translate(binding.tvTrSource.text.toString())


        tts = TextToSpeech(this) { status ->
            if (TextToSpeech.SUCCESS == status) tts.setLanguage(
                Locale.getDefault()
            )
        }
        //  checkLastTranslationCollectedAndSetIcon()

    }

    private fun initClick() {
        binding.ivTrBack.setOnClickListener { onBackPressed() }
        binding.tvTrNewTrans.setOnClickListener { onBackPressed() }
        binding.ivReToPhoto.setOnClickListener {
            startActivity(Intent(this, PhotoImageActivity::class.java))
        }
        binding.ivTrCopy.setOnClickListener {
            copyToClipboard()
            FirebaseAnalyticsHelper.textTransCopyEvent()
        }
        binding.ivSourceClear.setOnClickListener { onBackPressed() }
        binding.ivSourceTts.setOnClickListener {
            readText(
                binding.tvTrSource.text.toString(),
                PreferenceLanguageUtils.getString("language_source"),
                this
            )
        }
        binding.ivTargetTts.setOnClickListener {
            readText(
                binding.tvTrTarget.text.toString(),
                PreferenceLanguageUtils.getString("language_target"),
                this
            )
            FirebaseAnalyticsHelper.textTransPlayEvent()
        }
        binding.ivTrTargetShare.setOnClickListener {
            shareText(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 checkLastTranslationCollectedAndSetIcon() {
        val dbTranslation = DbTranslation(this)
        val lastTranslationCollected = dbTranslation.isLastTranslationCollected
        updateCollectIcon(lastTranslationCollected)
    }


    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 = "translating..."
        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
                        addHistory(result)
                    } else {
                        // 处理错误信息
                        if (!TextUtils.isEmpty(errorMessage)) {
                            // 显示错误信息或记录日志
                            if (errorMessage != null) {
                                Log.e("TranslationError", errorMessage)
                            }
                        }
                        binding.tvTrTarget.text = "Translation failed: $errorMessage"
                    }
                }
            }

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

    }

    private fun addHistory(transResult: String?) {
        val dbTranslation = DbTranslation(this)
        val translations = Translations(
            PreferenceLanguageUtils.getString("language_source"),
            binding.tvTrSource.text.toString(),
            PreferenceLanguageUtils.getString("language_target"),
            transResult

        )
        dbTranslation.addTranslation(translations)
    }


    private fun shareText(text: String) {
        val share: String = text.trim()
        if (!TextUtils.isEmpty(share)) {
            val intent = Intent(Intent.ACTION_SEND)
            intent.setType("text/plain")
            intent.putExtra(Intent.EXTRA_TEXT, share)
            startActivity(Intent.createChooser(intent, "Share " + getString(R.string.app_name)))
        }
    }

    // readText 方法，整合获取语言代码和朗读文本功能
    private fun readText(text: String, targetLanguage: String, context: Context) {
        val speech: String = text.trim()
        if (!TextUtils.isEmpty(speech)) {
            // 获取目标语言的语言代码
            val languageCode =
                LanguagesConstants.getInstance().getLanguageCodeByLanguage(targetLanguage, context)
            Log.d("LanguageCode", "Language Code for $targetLanguage: $languageCode")

            // 创建语言 Locale 对象
            val locale = Locale(languageCode)

            // 判断语言是否支持
            if (TextToSpeech.LANG_NOT_SUPPORTED != tts.isLanguageAvailable(locale)) {
                tts.language = locale
                tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null, null)
            } else {
                Widget.makeToast(this, getString(R.string.tr_tts_error))
            }
        }
    }


    // 复制到粘贴板
    private fun copyToClipboard() {
        val tip = "Copied to clipboard!"
        val tipNull = "text is null!"
        val share = binding.tvTrTarget.text.toString().trim()
        if (!TextUtils.isEmpty(share)) {
            val clipboardManager =
                getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText("targetValue", share)
            clipboardManager.setPrimaryClip(clipData)
            Widget.makeToast(this, tip)
        } else {
            Widget.makeToast(this, tipNull)
        }
    }

    override fun onStop() {
        super.onStop()
        tts.stop()
    }

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

}