package com.eonbry.store

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {

    private val prefs by lazy { getSharedPreferences("app_prefs", Context.MODE_PRIVATE) }
    private lateinit var imgLogo: ImageView
    private var jobVerificacaoLogo: Job? = null

    private fun isAndroidTV(): Boolean {
        return packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imgLogo = findViewById(R.id.imgLogo)

        // Carrega a logo salva, se existir
        val urlLogoSalva = prefs.getString("logo_url", null)
        if (!urlLogoSalva.isNullOrEmpty()) {
            atualizarLogo(urlLogoSalva)
        }

        // Verifica no servidor se existe logo nova
        verificarLogoAtualizada()

        // Inicia verificação contínua a cada 5 minutos
        iniciarVerificacaoContinua()

        val cardSemCodigo = findViewById<LinearLayout>(R.id.cardSemCodigo)
        val cardComCodigo = findViewById<LinearLayout>(R.id.cardComCodigo)
        cardSemCodigo.requestFocus()

        val isTV = isAndroidTV()

        if (isTV) {
            cardSemCodigo.setOnClickListener {
                startActivity(Intent(this, WebViewActivity::class.java))
            }
            cardComCodigo.setOnClickListener {
                startActivity(Intent(this, WebViewActivitycodigo::class.java))
            }
        } else {
            cardSemCodigo.isFocusable = false
            cardSemCodigo.setOnClickListener {
                startActivity(Intent(this, WebViewActivity::class.java))
            }
            cardComCodigo.isFocusable = false
            cardComCodigo.setOnClickListener {
                startActivity(Intent(this, WebViewActivitycodigo::class.java))
            }
        }

        // Verifica atualização do app (aqui mantém seu UpdateManager)
        UpdateManager.verificarAtualizacao(this)
    }

    private fun verificarLogoAtualizada() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = URL("https://SEUHOST/SUAPASTA/logo/logo_version.json")
                val conn = url.openConnection() as HttpURLConnection
                val resposta = conn.inputStream.bufferedReader().use { it.readText() }

                val json = JSONObject(resposta)
                val urlLogo = json.getString("url")
                val versaoLogo = json.getString("version")

                val versaoSalva = prefs.getString("logo_version", "")
                val urlLogoSalva = prefs.getString("logo_url", "")

                if (versaoLogo != versaoSalva || urlLogo != urlLogoSalva) {
                    prefs.edit()
                        .putString("logo_version", versaoLogo)
                        .putString("logo_url", urlLogo)
                        .apply()

                    withContext(Dispatchers.Main) {
                        atualizarLogo(urlLogo)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun atualizarLogo(urlLogo: String) {
        Glide.with(this)
            .load(urlLogo)
            .placeholder(R.drawable.placeholder_logo)
            .error(R.drawable.error_logo)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true)
            .into(imgLogo)
    }

    private fun iniciarVerificacaoContinua() {
        jobVerificacaoLogo?.cancel()
        jobVerificacaoLogo = CoroutineScope(Dispatchers.Main).launch {
            while (isActive) {
                verificarLogoAtualizada()
                delay(5_000L) // 5S = 5.000 ms
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        jobVerificacaoLogo?.cancel()
    }
}

object UpdateManager {

    fun verificarAtualizacao(context: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = URL("https://SEUHOST/SUAPASTA/update/versao.json")
                val conn = url.openConnection() as HttpURLConnection
                val resposta = conn.inputStream.bufferedReader().use { it.readText() }

                val json = JSONObject(resposta)
                val versaoServidor = json.getString("versao")
                val mensagem = json.getString("mensagem")
                val apkUrl = json.getString("url_apk")

                val versaoAtual = context.packageManager.getPackageInfo(context.packageName, 0).versionName

                if (versaoServidor != versaoAtual) {
                    withContext(Dispatchers.Main) {
                        mostrarDialogAtualizacao(context, mensagem, apkUrl)
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun mostrarDialogAtualizacao(context: Context, mensagem: String, apkUrl: String) {
        val dialogView = android.view.LayoutInflater.from(context).inflate(R.layout.dialog_update, null)
        val txtMensagem = dialogView.findViewById<TextView>(R.id.txtMensagem)
        val btnAtualizar = dialogView.findViewById<Button>(R.id.btnAtualizar)
        val btnCancelar = dialogView.findViewById<Button>(R.id.btnCancelar)

        txtMensagem.text = mensagem
        btnAtualizar.requestFocus()

        val dialog = AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert)
            .setView(dialogView)
            .setCancelable(false)
            .create()

        btnAtualizar.setOnClickListener {
            dialog.dismiss()
            baixarEInstalarApk(context, apkUrl)
        }

        btnCancelar.setOnClickListener {
            dialog.dismiss()
        }

        dialog.show()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        val largura = (context.resources.displayMetrics.widthPixels * 0.8).toInt()
        dialog.window?.setLayout(largura, ViewGroup.LayoutParams.WRAP_CONTENT)
        dialog.window?.setGravity(Gravity.CENTER)
    }

    private fun baixarEInstalarApk(context: Context, urlApk: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = URL(urlApk)
                val connection = url.openConnection() as HttpURLConnection
                connection.connect()

                val input = BufferedInputStream(url.openStream())
                val file = File(context.getExternalFilesDir(null), "update.apk")
                val output = FileOutputStream(file)

                val data = ByteArray(1024)
                var count: Int
                while (input.read(data).also { count = it } != -1) {
                    output.write(data, 0, count)
                }

                output.flush()
                output.close()
                input.close()

                val apkUri = FileProvider.getUriForFile(
                    context,
                    "com.eonbry.store.provider",
                    file
                )

                val intent = Intent(Intent.ACTION_VIEW).apply {
                    setDataAndType(apkUri, "application/vnd.android.package-archive")
                    flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK
                }

                context.startActivity(intent)

            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    android.widget.Toast.makeText(context, "Erro ao instalar APK: ${e.message}", android.widget.Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}
