package com.dphms.netguard

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.Fragment

class NetworkFragment : Fragment() {

    private lateinit var output: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.tab_network, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        output = view.findViewById(R.id.tvNetOutput)

        // === DPHMS STORE banner ===
        view.findViewById<Button>(R.id.btnBannerProPlus).setOnClickListener {
            openPayPal("DPHMS Pro+ v4.0 - AI Terminal Edition", "DPHMS-PROPLUS-V4", "4.99", "proplus")
        }
        view.findViewById<Button>(R.id.btnBannerPro).setOnClickListener {
            openPayPal("DPHMS Pro v3.0 - Full 10-Tab Toolkit", "DPHMS-PRO-V3", "2.99", "pro")
        }
        view.findViewById<Button>(R.id.btnBannerBundle).setOnClickListener {
            openPayPal("DPHMS Complete Bundle - Pro+ + NetGuard + Source", "DPHMS-BUNDLE", "4.99", "bundle")
        }
        view.findViewById<Button>(R.id.btnBannerWebsite).setOnClickListener {
            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://dphms.vercel.app")))
        }

        // === QUICK NETWORK MODE ===
        view.findViewById<Button>(R.id.btnForce4G).setOnClickListener {
            execCommand("settings put global preferred_network_mode 11 && cmd phone set-preferred-network-type 11")
            appendOutput("→ Force 4G LTE Only (mode 11)")
        }

        view.findViewById<Button>(R.id.btnForce5G).setOnClickListener {
            execCommand("settings put global preferred_network_mode 23 && cmd phone set-preferred-network-type 23")
            appendOutput("→ Force 5G SA Only (mode 23)")
        }

        view.findViewById<Button>(R.id.btnHybrid5G4G).setOnClickListener {
            execCommand("settings put global preferred_network_mode 24 && cmd phone set-preferred-network-type 24")
            appendOutput("→ 5G + 4G Hybrid (mode 24) — Recommended for Visible")
        }

        view.findViewById<Button>(R.id.btnAuto5G).setOnClickListener {
            execCommand("settings put global preferred_network_mode 27 && cmd phone set-preferred-network-type 27")
            appendOutput("→ Reset to Default 5G Auto (mode 27)")
        }

        view.findViewById<Button>(R.id.btnForce2G).setOnClickListener {
            execCommand("settings put global preferred_network_mode 1 && cmd phone set-preferred-network-type 1")
            appendOutput("→ Force 2G Only (mode 1) — Battery Saver")
        }

        // === PRESET BITMASK BUTTONS (one-tap apply) ===
        view.findViewById<Button>(R.id.btnPreset5G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000010000000000000")
            appendOutput("→ 5G NR Only: 00000010000000000000 (bit 13)")
        }

        view.findViewById<Button>(R.id.btnPreset4G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000000000100000000")
            appendOutput("→ 4G LTE Only: 00000000000100000000 (bit 8)")
        }

        view.findViewById<Button>(R.id.btnPreset5G4G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000010000100000000")
            appendOutput("→ 5G + 4G: 00000010000100000000 (bits 8+13)")
        }

        view.findViewById<Button>(R.id.btnPreset3G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000001110000000100")
            appendOutput("→ 3G Only (WCDMA+HSPA): 00000001110000000100 (bits 2,9,10,11)")
        }

        view.findViewById<Button>(R.id.btnPreset2G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000000000001100001")
            appendOutput("→ 2G Only (GSM+GPRS+EDGE): 00000000000001100001 (bits 0,5,6)")
        }

        view.findViewById<Button>(R.id.btnPreset4G3G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000001110000100100")
            appendOutput("→ 4G + 3G: 00000001110000100100 (bits 2,8,9,10,11)")
        }

        view.findViewById<Button>(R.id.btnPreset5G4G3G).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 00000011110000100100")
            appendOutput("→ 5G + 4G + 3G: 00000011110000100100 (bits 2,8,9,10,11,13)")
        }

        view.findViewById<Button>(R.id.btnPresetAll).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 11111111111111111111")
            appendOutput("→ All Network Types: 11111111111111111111 (reset)")
        }

        view.findViewById<Button>(R.id.btnPresetUser).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user 01000001000000000000")
            appendOutput("→ User Preset: 01000001000000000000")
        }

        // === ADVANCED BITMASK (manual) ===
        view.findViewById<Button>(R.id.btnApplyBitmask).setOnClickListener {
            val subId = view.findViewById<EditText>(R.id.etSubId).text.toString().ifEmpty { "1" }
            val bitmask = view.findViewById<EditText>(R.id.etBitmask).text.toString()
            execCommand("cmd phone set-allowed-network-types-for-users -s $subId user $bitmask")
            appendOutput("→ Applied bitmask: $bitmask (subId=$subId)")
        }

        // Load presets into text field
        view.findViewById<Button>(R.id.btnBitmaskLTE).setOnClickListener {
            view.findViewById<EditText>(R.id.etBitmask).setText("00000000000100000000")
            appendOutput("→ Preset loaded: LTE Only (bit 8)")
        }

        view.findViewById<Button>(R.id.btnBitmaskNR_LTE).setOnClickListener {
            view.findViewById<EditText>(R.id.etBitmask).setText("00000010000100000000")
            appendOutput("→ Preset loaded: NR + LTE (bits 8+13)")
        }

        view.findViewById<Button>(R.id.btnBitmaskAll).setOnClickListener {
            view.findViewById<EditText>(R.id.etBitmask).setText("11111111111111111111")
            appendOutput("→ Preset loaded: All Types")
        }

        // === CLASSIC MODE ===
        view.findViewById<Button>(R.id.btnApplyMode).setOnClickListener {
            val mode = view.findViewById<EditText>(R.id.etNetworkMode).text.toString()
            if (mode.isNotEmpty()) {
                execCommand("settings put global preferred_network_mode $mode")
                appendOutput("→ settings put global preferred_network_mode $mode")
            }
        }

        view.findViewById<Button>(R.id.btnApplyModeCmd).setOnClickListener {
            val mode = view.findViewById<EditText>(R.id.etNetworkMode).text.toString()
            if (mode.isNotEmpty()) {
                execCommand("cmd phone set-preferred-network-type $mode")
                appendOutput("→ cmd phone set-preferred-network-type $mode")
            }
        }

        view.findViewById<Button>(R.id.btnQueryMode).setOnClickListener {
            execCommand("settings get global preferred_network_mode")
        }
    }

    private fun execCommand(cmd: String) {
        Thread {
            val service = ShizukuManager.getService()
            if (service == null) {
                appendOutput("ERROR: Shizuku not ready. Start Shizuku and grant permission.")
                return@Thread
            }
            val result = service.executeCommand(cmd)
            if (result.isNotBlank() && !result.startsWith("ERROR")) {
                appendOutput(result.trim())
            }
        }.start()
    }

    private fun appendOutput(text: String) {
        activity?.runOnUiThread {
            output.text = output.text.toString() + "\n" + text
        }
    }

    private fun openPayPal(itemName: String, itemNumber: String, amount: String, item: String) {
        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", "https://dphms.vercel.app/thank-you.html?item=$item")
            .appendQueryParameter("cancel_return", "https://dphms.vercel.app")
            .build()
        startActivity(Intent(Intent.ACTION_VIEW, url))
    }
}
