package com.siro.siro_driver

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.siro.siro_driver/security"
    private val APP_CONTROL_CHANNEL = "com.siro.siro_driver/app_control"
    private var appControlChannel: MethodChannel? = null

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

        appControlChannel =
                MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_CONTROL_CHANNEL)

        // 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)
        appControlChannel?.setMethodCallHandler { call, result ->
            when (call.method) {
                "bringToForeground" -> {
                    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)
                        result.success(true)
                    } catch (e: Exception) {
                        result.error("ACTIVITY_START_FAILED", e.message, e.stackTraceToString())
                    }
                }
                else -> result.notImplemented()
            }
        }

        // ✅ Channel for Android Auto Navigation Updates
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.siro.siro_driver/car_navigation")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "updateNavState" -> {
                        // تحديث شامل لجميع بيانات التوجيه دفعة واحدة
                        CarNavigationData.currentLat = call.argument<Double>("lat") ?: CarNavigationData.currentLat
                        CarNavigationData.currentLng = call.argument<Double>("lng") ?: CarNavigationData.currentLng
                        CarNavigationData.currentBearing = call.argument<Double>("bearing") ?: CarNavigationData.currentBearing
                        CarNavigationData.currentSpeed = call.argument<Double>("speed") ?: CarNavigationData.currentSpeed
                        CarNavigationData.currentInstruction = call.argument<String>("instruction") ?: CarNavigationData.currentInstruction
                        CarNavigationData.distanceToNextStepMeters = call.argument<Double>("distanceToStep") ?: CarNavigationData.distanceToNextStepMeters
                        CarNavigationData.totalDistanceRemainingMeters = call.argument<Double>("totalDistance") ?: CarNavigationData.totalDistanceRemainingMeters
                        CarNavigationData.estimatedTimeRemainingSeconds = call.argument<Double>("eta") ?: CarNavigationData.estimatedTimeRemainingSeconds
                        CarNavigationData.maneuverType = call.argument<Int>("maneuver") ?: CarNavigationData.maneuverType
                        CarNavigationData.isNavigating = call.argument<Boolean>("isNavigating") ?: CarNavigationData.isNavigating
                        CarNavigationData.notifyListeners()
                        result.success(true)
                    }
                    "updateLocation" -> {
                        CarNavigationData.currentLat = call.argument<Double>("lat") ?: 0.0
                        CarNavigationData.currentLng = call.argument<Double>("lng") ?: 0.0
                        CarNavigationData.currentBearing = call.argument<Double>("bearing") ?: CarNavigationData.currentBearing
                        CarNavigationData.currentSpeed = call.argument<Double>("speed") ?: CarNavigationData.currentSpeed
                        CarNavigationData.notifyListeners()
                        result.success(true)
                    }
                    "updateInstruction" -> {
                        CarNavigationData.currentInstruction = call.argument<String>("instruction") ?: ""
                        CarNavigationData.maneuverType = call.argument<Int>("maneuver") ?: 0
                        CarNavigationData.distanceToNextStepMeters = call.argument<Double>("distanceToStep") ?: 0.0
                        CarNavigationData.notifyListeners()
                        result.success(true)
                    }
                    "stopNavigation" -> {
                        CarNavigationData.isNavigating = false
                        CarNavigationData.currentInstruction = "تمت الرحلة بنجاح!"
                        CarNavigationData.notifyListeners()
                        result.success(true)
                    }
                    else -> result.notImplemented()
                }
            }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isDeviceCompromised()) {
            showSecurityWarningDialog()
        }
        // ✅ فحص هل التطبيق فتح بسبب زر "قبول" في النافذة
        checkIntentForOverlayAccept(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        // ✅ فحص النية (Intent) عند فتح التطبيق من الخلفية
        checkIntentForOverlayAccept(intent)
    }

    // 🔥 هذه الدالة السحرية التي تلتقط زر القبول وترسله للتطبيق الرئيسي 🔥
    private fun checkIntentForOverlayAccept(intent: Intent) {
        val acceptedTripId = intent.getStringExtra("acceptedTripId")
        if (acceptedTripId != null) {
            Log.d("MainActivity", "✅ Trip accepted via Native Intent: $acceptedTripId")
            appControlChannel?.invokeMethod("onOverlayTripAccepted", acceptedTripId)
            intent.removeExtra("acceptedTripId") // مسح النية لكي لا تتكرر
        }
    }

    // --- بقية كود الحماية الخاص بك ---
    private fun isDeviceCompromised(): Boolean {
        return try {
            val isRootedByRootBeer = RootBeer(this).isRooted
            isRootedByRootBeer
        } catch (e: Exception) {
            true
        }
    }

    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")
        } catch (e: Exception) {
            clearCache()
            clearAppData()
        }
        finishAffinity()
        System.exit(0)
    }

    private fun clearCache() {
        deleteDir(cacheDir)
        deleteDir(externalCacheDir)
    }

    private fun clearAppData() {}

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            dir.list()?.forEach { deleteDir(File(dir, it)) }
        }
        return dir?.delete() ?: false
    }
}
