package com.keyboard.journey

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.net.Uri
import android.os.Bundle
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.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ktx.immersionBar
import com.keyboard.journey.bean.ItemDataBean
import com.keyboard.journey.databinding.ActivityMainBinding
import com.keyboard.journey.topon.AdManager
import com.keyboard.journey.util.isMyInputMethodDefault
import com.keyboard.journey.util.isMyInputMethodEnabled
import com.keyboard.journey.util.openGooglePlayForReview
import com.keyboard.journey.util.shareAppInfo


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var backPressedOnce = false
    private lateinit var bannerStr0: String
    private lateinit var bannerStr1: String

    private val mFragments: MutableList<Fragment> = ArrayList()
    private var currentIndex: Int = 0
    private var mCurrentFragment: Fragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        bannerStr0 = getString(R.string.recommend)
        bannerStr1 = getString(R.string.cool)
        initBar()
        initView()
        registerReceiver()
        AdManager.loadAllAd()
    }

    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) {
        binding.apply {
            homeImg.setImageResource(
                when (index) {
                    0 -> {
                        binding.topLayout.visibility = View.VISIBLE
                        R.drawable.kj_home_select_icon
                    }

                    else -> R.drawable.kj_home_unselect_icon
                }
            )
            likeImg.setImageResource(
                when (index) {
                    1 -> {
                        binding.topLayout.visibility = View.GONE
                        R.drawable.kj_like_select_icon
                    }

                    else -> R.drawable.kj_like_unselect_icon
                }
            )
        }
    }

    override fun onResume() {
        super.onResume()
        updateSetMyInputMethod()
        updateSetMyInputMethodHome()
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    private fun setupDrawerListener() {
        binding.drawer.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {
                drawerView.isClickable = true
            }

            override fun onDrawerClosed(drawerView: View) {}

            override fun onDrawerStateChanged(newState: Int) {}
        })
    }

    private fun initClick() {
        binding.menuBtn.setOnClickListener {
            if (binding.drawer.isDrawerOpen(GravityCompat.START)) {
                binding.drawer.closeDrawer(GravityCompat.START)
            } else {
                binding.drawer.openDrawer(GravityCompat.START)
            }
        }

        binding.homeBtn.setOnClickListener {
            changeFragment(0)
            updateBtnState(0)
        }
        binding.likeBtn.setOnClickListener {
            changeFragment(1)
            updateBtnState(1)
        }
        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 = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imeManager.showInputMethodPicker()
        }

        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.dialogStepLayout.setOnClickListener {
            binding.dialogStepLayout.visibility = View.GONE
        }

        binding.dialogHomeStepLayout.setOnClickListener {
            binding.dialogHomeStepLayout.visibility = View.GONE
        }

        binding.privacyBtn.setOnClickListener {
            val privacyPolicyUrl = "https://sites.google.com/view/privacy-policy-html-app"
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse(privacyPolicyUrl)
            startActivity(intent)
        }
        binding.shareBtn.setOnClickListener {
            shareAppInfo(this)
        }
        binding.rateBtn.setOnClickListener {
            openGooglePlayForReview(this)
        }
    }

    override fun onBackPressed() {
        if (binding.drawer.isDrawerOpen(GravityCompat.START)) {
            binding.drawer.closeDrawer(GravityCompat.START);
        } else {
            if (backPressedOnce) {
                super.onBackPressed()
                return
            }

            backPressedOnce = true
            Toast.makeText(this, "Press again to exit!", Toast.LENGTH_SHORT).show()
            // 两秒钟内再次按返回键取消退出操作
            val handler = android.os.Handler()
            handler.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()
        setupDrawerListener()
        initClick()
    }

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

    private fun updateSetMyInputMethodHome() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)
        if (enabled) {
            binding.step1HomeBtn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step1HomeBtn.text = "Step 1:Enabled"
            binding.step1HomeBtn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step1HomeBtn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step1HomeBtn.text = "Step 1:Select"
            binding.step1HomeBtn.setTextColor(Color.parseColor("#000000"))
        }
        if (default) {
            binding.step2HomeBtn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step2HomeBtn.text = "Step 2:Enabled"
            binding.step1HomeBtn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step2HomeBtn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step2HomeBtn.text = "Step 2:Select"
            binding.step1HomeBtn.setTextColor(Color.parseColor("#000000"))
        }
    }


    private fun showDialogRecommend() {
        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, JourneyDetailsActivity::class.java)
            intent.putExtra(JourneyDetailsActivity.KEY_JOURNEY_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()
    }

}