package com.service_intaleq

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.setPadding
import com.scottyab.rootbeer.RootBeer
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.util.Timer
import kotlin.concurrent.schedule

class MainActivity : FlutterFragmentActivity() {
    private val SECURITY_CHANNEL = "com.service_intaleq/security"
    private val APP_CONTROL_CHANNEL = "com.service_intaleq/app_control"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        // Channel for security checks (isRooted)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SECURITY_CHANNEL)
                .setMethodCallHandler { call, result ->
                    when (call.method) {
                        "isNativeRooted" -> result.success(isDeviceCompromised())
                        else -> result.notImplemented()
                    }
                }

        // Channel for app control (bringing to foreground)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_CONTROL_CHANNEL)
                .setMethodCallHandler { call, result ->
                    when (call.method) {
                        "bringToForeground" -> {
                            Log.d("MainActivity", "Received bringToForeground request")
                            val intent =
                                    Intent(this, MainActivity::class.java).apply {
                                        action = Intent.ACTION_MAIN
                                        addCategory(Intent.CATEGORY_LAUNCHER)
                                        addFlags(
                                                Intent.FLAG_ACTIVITY_NEW_TASK or
                                                        Intent.FLAG_ACTIVITY_CLEAR_TOP or
                                                        Intent.FLAG_ACTIVITY_SINGLE_TOP
                                        )
                                    }
                            try {
                                startActivity(intent)
                                Log.d(
                                        "MainActivity",
                                        "App brought to foreground successfully with flags: ${intent.flags}"
                                )
                                result.success(true)
                            } catch (e: Exception) {
                                Log.e(
                                        "MainActivity",
                                        "Error bringing app to foreground: ${e.message}",
                                        e
                                )
                                result.error(
                                        "ACTIVITY_START_FAILED",
                                        e.message,
                                        e.stackTraceToString()
                                )
                            }
                        }
                        else -> result.notImplemented()
                    }
                }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("MainActivity", "MainActivity onCreate")
        if (isDeviceCompromised()) {
            showSecurityWarningDialog()
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        Log.d("MainActivity", "Received new intent: ${intent.action}, flags: ${intent.flags}")
    }

    private fun isDeviceCompromised(): Boolean {
        return try {
            val isRootedByRootBeer = RootBeer(this).isRooted
            Log.d("MainActivity", "Root check result: $isRootedByRootBeer")
            isRootedByRootBeer
        } catch (e: Exception) {
            Log.e("MainActivity", "Security check error: ${e.message}", e)
            true // Fail-safe: assume compromised if check fails
        }
    }

    private fun showSecurityWarningDialog() {
        var secondsRemaining = 10
        val progressBar =
                ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
                    max = 10
                    progress = 10
                }
        val textView =
                TextView(this).apply {
                    text = getString(R.string.security_warning_message)
                    textAlignment = TextView.TEXT_ALIGNMENT_CENTER
                }
        val layout =
                LinearLayout(this).apply {
                    orientation = LinearLayout.VERTICAL
                    setPadding(48)
                    addView(textView)
                    addView(progressBar)
                }
        val dialog =
                AlertDialog.Builder(this)
                        .setTitle(getString(R.string.security_warning_title))
                        .setView(layout)
                        .setCancelable(false)
                        .create()
        dialog.show()
        val timer = Timer()
        timer.schedule(0, 1000) {
            secondsRemaining--
            runOnUiThread {
                progressBar.progress = secondsRemaining
                if (secondsRemaining <= 0) {
                    timer.cancel()
                    dialog.dismiss()
                    clearAppDataAndExit()
                }
            }
        }
    }

    private fun clearAppDataAndExit() {
        try {
            Runtime.getRuntime().exec("pm clear $packageName")
            Log.d("MainActivity", "Cleared app data via package manager")
        } catch (e: Exception) {
            Log.e("MainActivity", "Error clearing app data: ${e.message}", e)
            clearCache()
            clearAppData()
        }
        finishAffinity()
        System.exit(0)
    }

    private fun clearCache() {
        deleteDir(cacheDir)
        deleteDir(externalCacheDir)
        Log.d("MainActivity", "Cleared cache directories")
    }

    private fun clearAppData() {
        // Be careful with this, it deletes all app data.
        // deleteDir(applicationContext.dataDir)
        Log.d("MainActivity", "App data clearing skipped (commented out)")
    }

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            dir.list()?.forEach { deleteDir(File(dir, it)) }
        }
        val deleted = dir?.delete() ?: false
        Log.d("MainActivity", "Deleted directory ${dir?.path}: $deleted")
        return deleted
    }
}
