package com.assimilate.alltrans.viewui

import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.MenuInflater
import android.view.View
import android.widget.RatingBar
import android.widget.TextView
import android.widget.Toast
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.R
import com.assimilate.alltrans.databinding.ActivitySettingsBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.util.Locale


class SettingsActivity
    : AppCompatActivity() {
    private lateinit var binding: ActivitySettingsBinding
    private lateinit var bottomSheetDialog: BottomSheetDialog
    private var userChoose = 1

    private val languageCodes = mutableListOf("en", "zh")

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

        initView()
        initClick()
    }

    private fun initView() {
        setBottomSheet()
        setVersion()

    }

    private fun initClick() {

//       binding.llLanguages.setOnClickListener(this::showLanguagePopup)

        binding.ivSetBack.setOnClickListener { finish() }
        binding.llRate.setOnClickListener {
            bottomSheetDialog.show()

        }
        binding.llFavorite.setOnClickListener {
            val intent = Intent(this, HistoryActivity::class.java)
            intent.putExtra("remove", "remove_history")

            startActivity(intent)
        }

        binding.llPrivacyPolicy.setOnClickListener {
            val url = "https://translark-privacy.mystrikingly.com"
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse(url)
            startActivity(intent)
        }
        binding.llShareApp.setOnClickListener {
            val textDescription = "choose please."
            val intentShare = Intent().setAction(Intent.ACTION_SEND).setType("text/plain")
            var sAux = "\n" + getString(R.string.app_name) + "\n\n"
            sAux += "https://play.google.com/store/apps/details?id=" + this.packageName
            intentShare.putExtra(Intent.EXTRA_TEXT, sAux)
            startActivity(Intent.createChooser(intentShare, textDescription))
        }

    }

    private fun setVersion() {
        try {
            // 获取 PackageInfo 对象
            val packageInfo = packageManager.getPackageInfo(packageName, 0)
            val versionName = packageInfo.versionName
            val versionCode =
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                    packageInfo.longVersionCode
                } else {
                    @Suppress("DEPRECATION")
                    packageInfo.versionCode.toLong()
                }

            // 将版本信息设置到 TextView
            binding.tvVersion.text = versionName.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            binding.tvVersion.text = "1.1.1"
        }
    }

    private fun setBottomSheet() {
        // 设置 BottomSheetDialog
        bottomSheetDialog = BottomSheetDialog(this, R.style.CustomBottomSheetDialogTheme)
        bottomSheetDialog.setContentView(R.layout.bottomsheet_rate)
        bottomSheetDialog.dismissWithAnimation = true

        bottomSheetDialog.findViewById<TextView>(R.id.tv_rate_commit)?.setOnClickListener {
            toGoogleStar()
            bottomSheetDialog.dismiss()
        }

        bottomSheetDialog.findViewById<RatingBar>(R.id.ratingBar)
            ?.setOnRatingBarChangeListener { _, rating, fromUser ->
                if (fromUser) {
                    userChoose = rating.toInt()
                }
            }
    }

    private fun toGoogleStar() {
        if (userChoose < 4) {
            // 显示感谢消息
            Toast.makeText(
                this,
                "Thank you for your feedback; we will strive to do better.",
                Toast.LENGTH_LONG
            ).show()

            bottomSheetDialog.dismiss()
        } else {

            // 构建 Google Play 评价页面的 URL
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))

            // 检查是否有能够处理这个 Intent 的应用（如 Google Play 应用）
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            } else {
                // 如果 Google Play 应用不可用，则打开浏览器中的 Google Play 页面
                val webIntent = Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
                )
                startActivity(webIntent)
            }

            bottomSheetDialog.dismiss()
        }
    }


    private fun showLanguagePopup(view: View) {
        val popupMenu = PopupMenu(this, view, Gravity.END)
        val inflater: MenuInflater = popupMenu.menuInflater
        inflater.inflate(R.menu.language_menu, popupMenu.menu)

        popupMenu.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.language_english -> {
                    setLocale(languageCodes[0])
                    return@setOnMenuItemClickListener true
                }

                R.id.language_chinese -> {
                    setLocale(languageCodes[1])
                    return@setOnMenuItemClickListener true
                }

                else -> return@setOnMenuItemClickListener false
            }
        }

        popupMenu.show()
    }

    private fun setLocale(lang: String) {
        val locale = Locale(lang)
        Locale.setDefault(locale)
        val config = Configuration()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale)
        } else {
            config.locale = locale
        }

        // 更新资源配置
        resources.updateConfiguration(config, resources.displayMetrics)
        // 创建新的配置上下文
        baseContext.createConfigurationContext(config)

//        // 保存用户选择的语言
//        val editor = getSharedPreferences("Settings", MODE_PRIVATE).edit()
//        editor.putString("My_Lang", lang)
//        editor.apply()

        // 重新启动Activity以应用语言更改
//        val intent = Intent(this, SettingsActivity::class.java)
//        startActivity(intent)
//        finish()
    }


}