package com.keyboard.craft.activity

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.applovin.sdk.AppLovinSdk
import com.bumptech.glide.Glide
import com.keyboard.craft.fragment.HomeFragment
import com.keyboard.craft.fragment.LikeFragment
import com.keyboard.craft.R
import com.keyboard.craft.ad.MaxManager
import com.keyboard.craft.bean.ItemDataBean
import com.keyboard.craft.databinding.ActivityMainBinding
import com.keyboard.craft.util.UIHelper
import com.keyboard.craft.util.isMyInputMethodDefault
import com.keyboard.craft.util.isMyInputMethodEnabled
import com.keyboard.craft.util.openGooglePlayForReview
import com.keyboard.craft.util.shareAppInfo


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var backPressedOnce = false
    private val mFragments: MutableList<Fragment> = ArrayList()
    private var currentIndex: Int = 0
    private var mCurrentFragment: Fragment? = null
    private val homeFragment = HomeFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        backPressedCallback()
        initBar()
        initView()
        registerReceiver()
    }


    private fun initFragment() {
        mFragments.clear()
        mFragments.add(homeFragment)
        mFragments.add(LikeFragment())
        changeFragment(0)
        updateBtnState(0)
    }

    private fun changeFragment(index: Int) {
        currentIndex = index
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (null != mCurrentFragment) {
            ft.hide(mCurrentFragment!!)
        }
        var fragment = supportFragmentManager.findFragmentByTag(
            mFragments[currentIndex].javaClass.name
        )
        if (null == fragment) {
            fragment = mFragments[index]
        }
        mCurrentFragment = fragment

        if (!fragment.isAdded) {
            ft.add(R.id.frame_layout, fragment, fragment.javaClass.name)
        } else {
            ft.show(fragment)
        }
        ft.commit()
    }

    private fun updateBtnState(index: Int) {
        val icons = listOf(
            Pair(R.drawable.home_select_icon, R.drawable.home_unselect_icon),
            Pair(R.drawable.main_like_select_icon, R.drawable.main_like_unselect_icon),
            Pair(R.drawable.home_settings_select_icon, R.drawable.home_settings_unselect_icon)
        )

        val imageViews = listOf(binding.homeImg, binding.likeImg)

        imageViews.forEachIndexed { i, imageView ->
            val (selectedIcon, unselectedIcon) = icons[i]
            imageView.setImageResource(if (i == index) selectedIcon else unselectedIcon)
        }
        if (index == 1) {
            binding.fgTitleTv.text = getString(R.string.my_favorite)
        } else {
            binding.fgTitleTv.text = getString(R.string.app_name)
        }
    }

    override fun onResume() {
        super.onResume()
        MaxManager.onLoadAd()
        updateSetMyInputMethodHome()
    }

    private fun initBar() {
        UIHelper.setupStatusBar(this, true, binding.view)
    }


    private fun initClick() {
        binding.homeBtn.setOnClickListener {
            changeFragment(0)
            updateBtnState(0)
        }
        binding.likeBtn.setOnClickListener {
            changeFragment(1)
            updateBtnState(1)
        }
        binding.step1HomeBtn.setOnClickListener {
            val intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)
            startActivity(intent)
        }
        binding.step2HomeBtn.setOnClickListener {
            val imeManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imeManager.showInputMethodPicker()
        }
        binding.dialogHomeStepLayout.setOnClickListener {
            binding.dialogHomeStepLayout.visibility = View.GONE
        }
        binding.drawerBtn.setOnClickListener {
            binding.drawerLayout.openDrawer(binding.drawerView)
        }
        binding.drawerView.setOnClickListener { }
        binding.applyKeyboardBtn.setOnClickListener {
            val enabled = isMyInputMethodEnabled(this)
            val default = isMyInputMethodDefault(this)
            if (enabled && default) {
                binding.dialogStepLayout.visibility = View.GONE

                Toast.makeText(
                    this, "The keyboard has been set up successfully!", Toast.LENGTH_SHORT
                ).show()
            } else {
                binding.dialogStepLayout.visibility = View.VISIBLE
                updateSetMyInputMethod()
            }
        }
        binding.step1Btn.setOnClickListener {
            val intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)
            startActivity(intent)
        }
        binding.step2Btn.setOnClickListener {
            val imeManager =
                this.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
            imeManager.showInputMethodPicker()
        }
        binding.dialogStepLayout.setOnClickListener {
            binding.dialogStepLayout.visibility = View.GONE
        }
        binding.shareBtn.setOnClickListener {
            shareAppInfo(this)
        }
        binding.rateBtn.setOnClickListener {
            openGooglePlayForReview(this)
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun updateSetMyInputMethod() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)
        if (enabled) {
            binding.step1Btn.background = this.getDrawable(R.drawable.drw_gray_select_bg)
            binding.step1Btn.text = "Step 1:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        } else {
            binding.step1Btn.background = this.getDrawable(R.drawable.drw_btn_bg)
            binding.step1Btn.text = "Step 1:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#ffffff"))
        }
        if (default) {
            binding.step2Btn.background = this.getDrawable(R.drawable.drw_gray_select_bg)
            binding.step2Btn.text = "Step 2:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        } else {
            binding.step2Btn.background = this.getDrawable(R.drawable.drw_btn_bg)
            binding.step2Btn.text = "Step 2:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#ffffff"))
        }
    }

    private fun backPressedCallback() {
        // 注册 OnBackPressedCallback
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (backPressedOnce) {
                    // 如果用户已经按过一次返回键，允许系统处理默认的返回操作
                    isEnabled = false
                    onBackPressedDispatcher.onBackPressed()
                } else {
                    backPressedOnce = true
                    Toast.makeText(this@MainActivity, "Press again to exit!", Toast.LENGTH_SHORT)
                        .show()

                    // 两秒钟内再次按返回键取消退出操作
                    Handler(Looper.getMainLooper()).postDelayed({
                        backPressedOnce = false
                    }, 2000)
                }
            }
        })
    }

    private fun initView() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)
        if (!enabled || !default) {
            binding.dialogHomeStepLayout.visibility = View.VISIBLE
            updateSetMyInputMethodHome()
        }

        initFragment()
        initClick()
    }

    private fun updateButtonState(
        button: TextView, enabled: Boolean, textResId: Int, colorResId: Int, backgroundResId: Int
    ) {
        button.text = getString(textResId)
        button.setTextColor(ContextCompat.getColor(this, colorResId))
        button.background = ContextCompat.getDrawable(this, backgroundResId)
    }

    private fun updateSetMyInputMethodHome() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)

        updateButtonState(
            binding.step1HomeBtn,
            enabled,
            if (enabled) R.string.step1_enabled else R.string.step1_select,
            if (enabled) R.color.black else R.color.white,
            if (enabled) R.drawable.drw_gray_select_bg else R.drawable.drw_btn_bg
        )

        updateButtonState(
            binding.step2HomeBtn,
            default,
            if (default) R.string.step2_enabled else R.string.step2_select,
            if (default) R.color.black else R.color.white,
            if (default) R.drawable.drw_gray_select_bg else R.drawable.drw_btn_bg
        )
    }


    private fun showDialogRecommend() {
        val dataList = homeFragment.dataList
        if (dataList.isNotEmpty()) {
            val list = homeFragment.getRandomItemsFromMainDataBeans(dataList, 1)
            val bean = list?.get(0)
            val inflater = LayoutInflater.from(this)
            val dialogView = inflater.inflate(R.layout.dialog_recommend, null)
            val okBtn = dialogView.findViewById<ImageView>(R.id.go_btn)
            val cancelBtn = dialogView.findViewById<LinearLayout>(R.id.cha_btn)
            val img = dialogView.findViewById<ImageView>(R.id.img)
            Glide.with(this).load(bean?.thumbUrl).into(img)
            val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
            val dialog = dialogBuilder.create()
            dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            dialog.show()
            okBtn.setOnClickListener {
                dialog.dismiss()
                val intent = Intent(this, DetailsActivity::class.java)
                intent.putExtra(DetailsActivity.KEY_CRAFT_DETAILS_BEAN, bean)
                startActivity(intent)
            }
            cancelBtn.setOnClickListener {
                dialog.dismiss()
            }
        } else {
            val bean = ItemDataBean(
                isLiked = false,
                key = "225e68e251874193a884d7dd4b718586",
                title = "AIGC Pretty Heart Girl",
                type = 6,
                thumbUrl = "https://cdn.kikakeyboard.com/picture/wallpaper/1705373685197_keyboard_preview_604*444.jpg.webp",
                thumbUrlGif = ""
            )

            val inflater = LayoutInflater.from(this)
            val dialogView = inflater.inflate(R.layout.dialog_recommend, null)
            val okBtn = dialogView.findViewById<ImageView>(R.id.go_btn)
            val cancelBtn = dialogView.findViewById<LinearLayout>(R.id.cha_btn)
            val img = dialogView.findViewById<ImageView>(R.id.img)
            Glide.with(this).load(bean.thumbUrl).into(img)
            val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
            val dialog = dialogBuilder.create()
            dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            dialog.show()
            okBtn.setOnClickListener {
                dialog.dismiss()
                val intent = Intent(this, DetailsActivity::class.java)
                intent.putExtra(DetailsActivity.KEY_CRAFT_DETAILS_BEAN, bean)
                startActivity(intent)
            }
            cancelBtn.setOnClickListener {
                dialog.dismiss()
            }
        }
    }

    private var receiver: BroadcastReceiver? = null
    private fun registerReceiver() {
        val filter = IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED)
        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                updateSetMyInputMethodHome()
                val enabled = isMyInputMethodEnabled(this@MainActivity)
                val default = isMyInputMethodDefault(this@MainActivity)
                if (enabled && default) {
                    binding.dialogHomeStepLayout.visibility = View.GONE
                    if (!isFinishing && !isDestroyed) {
                        showDialogRecommend()
                    }
                } else {
                    binding.dialogHomeStepLayout.visibility = View.VISIBLE
                }
            }
        }
        registerReceiver(receiver, filter)
    }

    private fun unregisterReceiver() {
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver()
    }

}