package com.dphms.netguard

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.core.content.ContextCompat

class ScanResultAdapter(private val results: List<ScanResult>) : RecyclerView.Adapter<ScanResultAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvPkg: TextView = view.findViewById(R.id.tvResultPkg)
        val tvDetails: TextView = view.findViewById(R.id.tvResultDetails)
        val tvSeverity: TextView = view.findViewById(R.id.tvResultSeverity)
        val btnSettings: Button = view.findViewById(R.id.btnResultSettings)
        val btnShizuku: Button = view.findViewById(R.id.btnResultShizuku)
        val btnPro: Button = view.findViewById(R.id.btnResultPro)
        val btnProPlus: Button = view.findViewById(R.id.btnResultProPlus)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.scan_result_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val result = results[position]
        holder.tvPkg.text = result.pkg

        val permText = if (result.permissions.isNotEmpty()) {
            result.permissions.joinToString("\n") { "  • $it" }
        } else ""
        holder.tvDetails.text = result.details + if (permText.isNotEmpty()) "\n$permText" else ""

        holder.tvSeverity.text = result.severity
        val color = when (result.severity) {
            "CRITICAL" -> R.color.accent_red
            "HIGH" -> R.color.accent_red
            "MEDIUM" -> R.color.accent_amber
            "LOW" -> R.color.accent_cyan
            else -> R.color.text_secondary
        }
        holder.tvSeverity.setTextColor(ContextCompat.getColor(holder.itemView.context, color))

        // Settings button → open app settings
        holder.btnSettings.setOnClickListener {
            val context = holder.itemView.context
            try {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.parse("package:${result.pkg}")
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(intent)
            } catch (e: Exception) { }
        }

        // Shizuku button → open app info via Shizuku shell
        holder.btnShizuku.setOnClickListener {
            val context = holder.itemView.context
            val service = ShizukuManager.getService()
            if (service != null) {
                try {
                    service.executeCommand("am start -a android.settings.APPLICATION_DETAILS_SETTINGS -d package:${result.pkg}")
                } catch (e: Exception) { }
            } else {
                Toast.makeText(context, "Shizuku not connected", Toast.LENGTH_SHORT).show()
            }
        }

        // Pro button → try to open DPHMS Pro app, fall back to PayPal
        holder.btnPro.setOnClickListener {
            val context = holder.itemView.context
            try {
                val intent = context.packageManager.getLaunchIntentForPackage("com.dphms.optimizer")
                if (intent != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                } else {
                    throw ActivityNotFoundException()
                }
            } catch (e: ActivityNotFoundException) {
                // App not installed → PayPal checkout for Pro
                val url = Uri.parse("https://www.paypal.com/cgi-bin/webscr")
                    .buildUpon()
                    .appendQueryParameter("cmd", "_xclick")
                    .appendQueryParameter("business", "ranicola12@gmail.com")
                    .appendQueryParameter("item_name", "DPHMS Pro v3.0 - Full 10-Tab Toolkit")
                    .appendQueryParameter("item_number", "DPHMS-PRO-V3")
                    .appendQueryParameter("amount", "2.99")
                    .appendQueryParameter("currency_code", "USD")
                    .appendQueryParameter("return", "https://dphms.vercel.app/thank-you.html?item=pro")
                    .appendQueryParameter("cancel_return", "https://dphms.vercel.app")
                    .build()
                context.startActivity(Intent(Intent.ACTION_VIEW, url))
            }
        }

        // Pro+ button → try to open DPHMS Pro+ app, fall back to PayPal
        holder.btnProPlus.setOnClickListener {
            val context = holder.itemView.context
            try {
                val intent = context.packageManager.getLaunchIntentForPackage("com.dphms.optimizer")
                if (intent != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                } else {
                    throw ActivityNotFoundException()
                }
            } catch (e: ActivityNotFoundException) {
                // App not installed → PayPal checkout for Pro+
                val url = Uri.parse("https://www.paypal.com/cgi-bin/webscr")
                    .buildUpon()
                    .appendQueryParameter("cmd", "_xclick")
                    .appendQueryParameter("business", "ranicola12@gmail.com")
                    .appendQueryParameter("item_name", "DPHMS Pro+ v4.0 - AI Terminal Edition")
                    .appendQueryParameter("item_number", "DPHMS-PROPLUS-V4")
                    .appendQueryParameter("amount", "4.99")
                    .appendQueryParameter("currency_code", "USD")
                    .appendQueryParameter("return", "https://dphms.vercel.app/thank-you.html?item=proplus")
                    .appendQueryParameter("cancel_return", "https://dphms.vercel.app")
                    .build()
                context.startActivity(Intent(Intent.ACTION_VIEW, url))
            }
        }
    }

    override fun getItemCount() = results.size
}
