package com.keyboard.craft.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.keyboard.craft.R
import com.keyboard.craft.ad.MaxManager
import com.keyboard.craft.databinding.UiPreviewActivityBinding
import com.keyboard.craft.util.UIHelper
import com.keyboard.craft.util.currentlyThemeUFileString
import com.keyboard.craft.util.getBitmapXXDrawable
import com.keyboard.craft.util.isMyInputMethodDefault
import com.keyboard.craft.util.isMyInputMethodEnabled
import com.keyboard.craft.util.loadAndBlurImage

class PreviewActivity : AppCompatActivity() {

    private lateinit var binding: UiPreviewActivityBinding

    private var themeUrl = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = UiPreviewActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initBar()
        initializeData()
        registerReceiver()
        initView()
    }

    private fun initializeData() {
        themeUrl = intent.getStringExtra(KEY_PREVIEW_URL).orEmpty()
    }

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

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

    private fun initView() {
        val currentlyThemeUFile = currentlyThemeUFileString(this, themeUrl)
        loadAndBlurImage(
            this,
            getBitmapXXDrawable(this, currentlyThemeUFile, "keyboard_preview_screenshot.jpg"),
            binding.previewIv
        )

        val imagePath =
            "$currentlyThemeUFile/res/drawable-xxhdpi-v4/keyboard_preview.jpg"
        val bitmap = BitmapFactory.decodeFile(imagePath)
        val background = BitmapDrawable(resources, bitmap)
        binding.keyboardIv.background = background

        binding.backBtn.setOnClickListener { onBackPressed() }

        binding.activateBtn.setOnClickListener {
            binding.dialogStepLayout.visibility = View.VISIBLE
        }

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

    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 updateSetMyInputMethod() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)

        updateButtonState(
            binding.step1Btn,
            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.step2Btn,
            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
        )

        binding.edit.visibility = if (enabled && default) View.VISIBLE else View.GONE
        binding.tv.visibility = if (enabled && default) View.GONE else View.VISIBLE

        if (enabled && default) {
            binding.unauthorizedLayout.visibility = View.INVISIBLE
            showKeyboard(binding.edit)
        }
    }

    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) {
                updateSetMyInputMethod()
                val enabled = isMyInputMethodEnabled(this@PreviewActivity)
                val default = isMyInputMethodDefault(this@PreviewActivity)
                if (enabled && default) {
                    binding.dialogStepLayout.visibility = View.GONE
                    binding.edit.visibility = View.VISIBLE
                    binding.tv.visibility = View.GONE
                    showKeyboard(binding.edit)
                } else {
                    binding.dialogStepLayout.visibility = View.VISIBLE
                }
            }
        }
        registerReceiver(receiver, filter)
    }

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

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

    private fun showKeyboard(view: View) {
        Handler(Looper.getMainLooper()).postDelayed({
            view.requestFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        }, 1000)
    }

    companion object {
        const val KEY_PREVIEW_URL = "key_preview_url"
    }

}