package com.dphms.optimizer.lite

import java.util.Locale
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

    private lateinit var ramBar: ProgressBar
    private lateinit var ramText: TextView
    private lateinit var storageBar: ProgressBar
    private lateinit var storageText: TextView
    private lateinit var btnStop: Button
    private lateinit var btnClear: Button
    private lateinit var progressBar: ProgressBar
    private lateinit var statusText: TextView
    private lateinit var currentOpText: TextView
    private lateinit var resultText: TextView
    private lateinit var shizukuStatusDot: View
    private lateinit var shizukuStatusText: TextView
    private lateinit var btnOpenShizuku: Button

    private val handler = Handler(Looper.getMainLooper())
    private var autoLaunchedShizuku = false

    private val updateRunnable = object : Runnable {
        override fun run() { updateSystemInfo(); handler.postDelayed(this, 3000) }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "DPHMS Lite"

        ramBar = findViewById(R.id.ram_bar)
        ramText = findViewById(R.id.ram_text)
        storageBar = findViewById(R.id.storage_bar)
        storageText = findViewById(R.id.storage_text)
        btnStop = findViewById(R.id.btn_stop)
        btnClear = findViewById(R.id.btn_clear)
        progressBar = findViewById(R.id.progress_bar)
        statusText = findViewById(R.id.status_text)
        currentOpText = findViewById(R.id.current_op_text)
        resultText = findViewById(R.id.result_text)
        shizukuStatusDot = findViewById(R.id.shizuku_status_dot)
        shizukuStatusText = findViewById(R.id.shizuku_status_text)
        btnOpenShizuku = findViewById(R.id.btn_open_shizuku)

        ShizukuManager.addPermissionResultListener { _, _ ->
            lifecycleScope.launch(Dispatchers.Main) { checkShizukuStatus() }
        }

        ShizukuManager.addBinderListeners(
            onReceived = { lifecycleScope.launch(Dispatchers.Main) { checkShizukuStatus() } },
            onDead = { lifecycleScope.launch(Dispatchers.Main) { checkShizukuStatus() } }
        )

        btnOpenShizuku.setOnClickListener { ShizukuManager.launchShizukuApp(this) }
        btnStop.setOnClickListener { performStopAll() }
        btnClear.setOnClickListener { performClearCaches() }

        checkShizukuStatus()
        updateSystemInfo()
        handler.post(updateRunnable)
    }

    private fun checkShizukuStatus() {
        when {
            !ShizukuManager.isShizukuInstalled(this) -> {
                shizukuStatusDot.setBackgroundColor(Color.parseColor("#FF2A2A"))
                shizukuStatusText.text = "Shizuku: Not Installed"
                shizukuStatusText.setTextColor(Color.parseColor("#FF2A2A"))
                btnOpenShizuku.visibility = View.GONE
                btnStop.isEnabled = false
                btnClear.isEnabled = false
            }
            !ShizukuManager.isShizukuRunning() -> {
                shizukuStatusDot.setBackgroundColor(Color.parseColor("#FFAA00"))
                shizukuStatusText.text = "Shizuku: Not Running"
                shizukuStatusText.setTextColor(Color.parseColor("#FFAA00"))
                btnOpenShizuku.visibility = View.VISIBLE
                btnStop.isEnabled = false
                btnClear.isEnabled = false
                if (!autoLaunchedShizuku) {
                    autoLaunchedShizuku = true
                    ShizukuManager.launchShizukuApp(this)
                }
            }
            !ShizukuManager.hasPermission() -> {
                shizukuStatusDot.setBackgroundColor(Color.parseColor("#FFAA00"))
                shizukuStatusText.text = "Shizuku: Permission Needed"
                shizukuStatusText.setTextColor(Color.parseColor("#FFAA00"))
                btnOpenShizuku.visibility = View.GONE
                btnStop.isEnabled = false
                btnClear.isEnabled = false
                ShizukuManager.requestPermission()
            }
            else -> {
                shizukuStatusDot.setBackgroundColor(Color.parseColor("#00FF66"))
                shizukuStatusText.text = "Shizuku: Connected"
                shizukuStatusText.setTextColor(Color.parseColor("#00FF66"))
                btnOpenShizuku.visibility = View.GONE
                btnStop.isEnabled = true
                btnClear.isEnabled = true
            }
        }
    }

    private fun updateSystemInfo() {
        lifecycleScope.launch(Dispatchers.Main) {
            val (ram, storage) = withContext(Dispatchers.IO) {
                try {
                    val reader = java.io.BufferedReader(java.io.InputStreamReader(
                        Runtime.getRuntime().exec(arrayOf("sh", "-c", "cat /proc/meminfo")).inputStream))
                    var total = 0L; var avail = 0L
                    var line: String?
                    while (reader.readLine().also { line = it } != null) {
                        val l = line ?: continue
                        if (l.startsWith("MemTotal:")) total = l.split(Regex("\\s+"))[1].toLong()
                        else if (l.startsWith("MemAvailable:")) avail = l.split(Regex("\\s+"))[1].toLong()
                    }
                    reader.close()
                    val stat = android.os.StatFs(android.os.Environment.getDataDirectory().path)
                    Pair(
                        Triple(total / 1024, avail / 1024, (total - avail) / 1024),
                        Triple(stat.totalBytes, stat.availableBytes, stat.totalBytes - stat.availableBytes)
                    )
                } catch (e: Exception) {
                    Pair(Triple(0L, 0L, 0L), Triple(0L, 0L, 0L))
                }
            }

            val (ramTotal, ramAvail, ramUsed) = ram
            val ramPct = if (ramTotal > 0) ((ramUsed.toFloat() / ramTotal) * 100).toInt() else 0
            ramBar.progress = ramPct
            ramText.text = "RAM: $ramUsed/$ramTotal MB ($ramPct%)"

            val (sTotal, sFree, sUsed) = storage
            val sTotalGb = sTotal / (1024.0 * 1024 * 1024)
            val sFreeGb = sFree / (1024.0 * 1024 * 1024)
            val sPct = if (sTotal > 0) ((sUsed.toFloat() / sTotal) * 100).toInt() else 0
            storageBar.progress = sPct
            storageText.text = "Storage: ${String.format(Locale.US, "%.1f", sFreeGb)} / ${String.format(Locale.US, "%.1f", sTotalGb)} GB ($sPct%)"
        }
    }

    private fun performStopAll() {
        btnStop.isEnabled = false; btnClear.isEnabled = false
        progressBar.visibility = View.VISIBLE
        statusText.text = "Stopping all apps..."
        resultText.text = ""

        lifecycleScope.launch(Dispatchers.Main) {
            val (stopped, ramFreed) = withContext(Dispatchers.IO) {
                try {
                    val service = ShizukuManager.bindService(this@MainActivity) ?: return@withContext Pair(0, 0L)
                    val optimizer = SystemOptimizer(service)
                    val ramBefore = optimizer.getRamInfo()
                    val stopped = optimizer.stopAllApps { current, total, pkg ->
                        runOnUiThread {
                            currentOpText.text = "Stopping $pkg ($current/$total)"
                            progressBar.progress = if (total > 0) (current * 100 / total) else 0
                        }
                    }
                    val ramAfter = optimizer.getRamInfo()
                    Pair(stopped, ramBefore.usedMb - ramAfter.usedMb)
                } catch (e: Exception) { Pair(0, 0L) }
            }

            progressBar.visibility = View.GONE
            statusText.text = "Complete"
            currentOpText.text = ""
            resultText.text = "$stopped apps stopped · ${ramFreed}MB RAM freed"
            btnStop.isEnabled = true; btnClear.isEnabled = true
            DPHMSWidgetProvider.updateAllWidgets(this@MainActivity)
        }
    }

    private fun performClearCaches() {
        btnStop.isEnabled = false; btnClear.isEnabled = false
        progressBar.visibility = View.VISIBLE
        statusText.text = "Clearing caches..."
        resultText.text = ""

        lifecycleScope.launch(Dispatchers.Main) {
            val (success, freedGb) = withContext(Dispatchers.IO) {
                try {
                    val service = ShizukuManager.bindService(this@MainActivity) ?: return@withContext Pair(false, 0.0)
                    val optimizer = SystemOptimizer(service)
                    val before = optimizer.getStorageInfo()
                    runOnUiThread { currentOpText.text = "Running pm trim-caches..." }
                    val result = optimizer.clearAllCaches()
                    val after = optimizer.getStorageInfo()
                    Pair(result, (after.freeGb - before.freeGb).coerceAtLeast(0.0))
                } catch (e: Exception) { Pair(false, 0.0) }
            }

            progressBar.visibility = View.GONE
            statusText.text = if (success) "Complete" else "Failed"
            currentOpText.text = ""
            resultText.text = if (success) "Cache cleared · ${String.format(Locale.US, "%.1f", freedGb)}GB freed"
                else "Clear failed — is Shizuku running?"
            btnStop.isEnabled = true; btnClear.isEnabled = true
            DPHMSWidgetProvider.updateAllWidgets(this@MainActivity)
        }
    }

    override fun onResume() {
        super.onResume()
        checkShizukuStatus()
        handler.post(updateRunnable)
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(updateRunnable)
    }

    fun openPayPal(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/donate/?business=ranicola12@gmail.com&currency_code=USD")))
    }

    fun openCashApp(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://cash.app/\$ranicola1")))
    }

    fun openWebsite(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://dphms.vercel.app/thank-you.html")))
    }

    fun buyPro(view: View) {
        openPayPalCheckout("DPHMS Pro v3.0 — Full 10-Tab Toolkit", "DPHMS-PRO-V3", "2.99", "pro")
    }

    fun buyNetGuard(view: View) {
        openPayPalCheckout("DPHMS NetGuard - Network & Security Scanner", "DPHMS-NETGUARD", "1.99", "netguard")
    }

    fun buyBundle(view: View) {
        openPayPalCheckout("DPHMS Complete Bundle — Pro+ + NetGuard + Source", "DPHMS-BUNDLE", "4.99", "bundle")
    }

    fun donate1(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/donate/?business=ranicola12@gmail.com&currency_code=USD&amount=1.00")))
    }

    fun donate5(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/donate/?business=ranicola12@gmail.com&currency_code=USD&amount=5.00")))
    }

    fun donate10(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/donate/?business=ranicola12@gmail.com&currency_code=USD&amount=10.00")))
    }

    fun donate20(view: View) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/donate/?business=ranicola12@gmail.com&currency_code=USD&amount=20.00")))
    }

    private fun openPayPalCheckout(itemName: String, itemNumber: String, amount: String, returnItem: String? = null) {
        val url = Uri.parse("https://www.paypal.com/cgi-bin/webscr")
            .buildUpon()
            .appendQueryParameter("cmd", "_xclick")
            .appendQueryParameter("business", "ranicola12@gmail.com")
            .appendQueryParameter("item_name", itemName)
            .appendQueryParameter("item_number", itemNumber)
            .appendQueryParameter("amount", amount)
            .appendQueryParameter("currency_code", "USD")
            .appendQueryParameter("return", if (returnItem != null) "https://dphms.vercel.app/thank-you.html?item=" + returnItem else "https://dphms.vercel.app/thank-you.html")
            .appendQueryParameter("cancel_return", "https://dphms.vercel.app")
            .build()
        startActivity(Intent(Intent.ACTION_VIEW, url))
    }
}
