package com.eonbry.store

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.webkit.URLUtil
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import java.io.File

class WebViewActivity : AppCompatActivity() {

    private lateinit var webView: WebView
    private lateinit var progressBar: ProgressBar
    private var downloadID: Long = -1
    private var downloadedFilePath: String? = null
    private lateinit var downloadManager: DownloadManager
    private val handler = Handler(Looper.getMainLooper())

    // Atualiza a barra de progresso
    private val updateProgress = object : Runnable {
        override fun run() {
            if (downloadID != -1L) {
                val query = DownloadManager.Query().setFilterById(downloadID)
                val cursor = downloadManager.query(query)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))
                    when (status) {
                        DownloadManager.STATUS_RUNNING -> {
                            val totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                            if (totalBytes > 0) {
                                val downloadedBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                                val progress = (downloadedBytes * 100 / totalBytes).toInt()
                                progressBar.progress = progress
                            }
                        }
                        DownloadManager.STATUS_SUCCESSFUL -> {
                            progressBar.progress = 100
                            handler.removeCallbacks(this)
                        }
                        DownloadManager.STATUS_FAILED -> {
                            handler.removeCallbacks(this)
                            progressBar.visibility = ProgressBar.GONE
                        }
                    }
                }
                cursor.close()
            }
            handler.postDelayed(this, 500) // Atualiza a cada 500ms
        }
    }

    // Verifica se é um dispositivo TV
    private fun isTvDevice(): Boolean {
        return (packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
                packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION))
    }

    // Injetar CSS para diminuir os cards em 40% em TVs
    private fun injectResizeScript() {
        val css = """
        @media only screen and (min-width: 960px) {
            .app-grid {
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 32px !important;
                padding: 0 20px;
            }

            .app-card {
                transform: none !important;
                transform-origin: center;
                width: 100% !important;
                height: auto !important;
                margin-bottom: 30px;
                font-size: 1.1rem !important;
            }

            .app-card:focus {
                transform: scale(1.06) !important;
                box-shadow: 0 0 45px #00f0ffcc, 0 0 65px #00f0ffaa;
                z-index: 2;
            }
        }
    """.trimIndent()

        val js = """
        var style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = `$css`;
        document.head.appendChild(style);
    """.trimIndent()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(js, null)
        } else {
            webView.loadUrl("javascript:$js")
        }
    }
    @SuppressLint("SetJavaScriptEnabled", "UnspecifiedRegisterReceiverFlag")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webviewcodigo)

        progressBar = findViewById(R.id.progressBar)
        progressBar.max = 100

        webView = findViewById(R.id.webView)
        webView.settings.javaScriptEnabled = true
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                if (isTvDevice()) {
                    injectResizeScript() // Aplica o redimensionamento apenas em TVs
                }
            }
        }
        webView.webChromeClient = WebChromeClient()
        webView.settings.setSupportZoom(true)
        webView.settings.builtInZoomControls = true
        webView.settings.displayZoomControls = false

        webView.setDownloadListener { url, userAgent, contentDisposition, mimeType, _ ->
            if (checkPermissions()) {
                val fileName = URLUtil.guessFileName(url, contentDisposition, mimeType)
                startDownload(url, userAgent, mimeType, fileName)
            } else {
                requestPermissions()
            }
        }

        webView.loadUrl("https://SEUHOST/SUAPASTA/loja.php")

        downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager

        val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(onDownloadComplete, filter, RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(onDownloadComplete, filter)
        }
    }

    private fun checkPermissions(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            true
        } else {
            ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                    PackageManager.PERMISSION_GRANTED
        }
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) return
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
            1001
        )
    }

    private fun startDownload(
        url: String,
        userAgent: String,
        mimeType: String,
        fileName: String
    ) {
        try {
            progressBar.progress = 0
            progressBar.visibility = ProgressBar.VISIBLE

            val request = DownloadManager.Request(Uri.parse(url)).apply {
                setMimeType(mimeType)
                addRequestHeader("User-Agent", userAgent)
                setTitle(fileName)
                setDescription("Baixando arquivo...")
                setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                setDestinationInExternalFilesDir(
                    this@WebViewActivity,
                    Environment.DIRECTORY_DOWNLOADS,
                    fileName
                )
            }

            downloadID = downloadManager.enqueue(request)
            handler.post(updateProgress)

            val file = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName)
            downloadedFilePath = file.absolutePath

            Toast.makeText(this, "Download iniciado...", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            progressBar.visibility = ProgressBar.GONE
            Toast.makeText(this, "Erro ao iniciar download: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private val onDownloadComplete = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (downloadID == id) {
                handler.removeCallbacks(updateProgress)
                progressBar.visibility = ProgressBar.GONE
                Toast.makeText(context, "Download concluído!", Toast.LENGTH_SHORT).show()
                showInstallDialog()
            }
        }
    }

    private fun showInstallDialog() {
        downloadedFilePath?.let { path ->
            AlertDialog.Builder(this)
                .setTitle("Instalação")
                .setMessage("Deseja instalar o aplicativo baixado?")
                .setPositiveButton("Instalar") { _, _ ->
                    openDownloadedApk(path)
                }
                .setNegativeButton("Cancelar", null)
                .show()
        }
    }

    private fun openDownloadedApk(filePath: String) {
        try {
            val file = File(filePath)
            if (file.exists()) {
                val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    FileProvider.getUriForFile(
                        this,
                        "${packageName}.provider",
                        file
                    )
                } else {
                    Uri.fromFile(file)
                }

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

                startActivity(intent)
            } else {
                Toast.makeText(this, "Arquivo não encontrado", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "Erro ao instalar: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateProgress)
        try {
            unregisterReceiver(onDownloadComplete)
        } catch (e: IllegalArgumentException) {
            // Ignora se o receiver não estiver registrado
        }
    }
}