package com.Intaleq.intaleq

import android.app.AlertDialog
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_NAME = "com.Intaleq.intaleq/security"
    private lateinit var securityChannel: MethodChannel

    // قناة تتبّع الرحلة (Live Activity على أندرويد)
    private val RIDE_TRACKING_CHANNEL = "intaleq/ride_tracking"

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

        // -------- 1) قناة الأمان --------
        securityChannel =
                MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SECURITY_CHANNEL_NAME)

        securityChannel.setMethodCallHandler { call, result ->
            when (call.method) {
                "isNativeRooted" -> {
                    val isCompromised = isDeviceCompromised()
                    result.success(isCompromised)
                }
                else -> {
                    result.notImplemented()
                }
            }
        }

        // -------- 2) قناة تتبع الرحلة (Ride Tracking) --------
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, RIDE_TRACKING_CHANNEL)
                .setMethodCallHandler { call, result ->
                    when (call.method) {
                        "updateRideTracking" -> {
                            val driverName = call.argument<String>("driverName") ?: "السائق"
                            val driverPhone = call.argument<String>("driverPhone") ?: ""
                            val carDetails = call.argument<String>("carDetails") ?: ""

                            val driverLat = call.argument<Double>("driverLat") ?: 0.0
                            val driverLng = call.argument<Double>("driverLng") ?: 0.0
                            val passengerLat = call.argument<Double>("passengerLat") ?: 0.0
                            val passengerLng = call.argument<Double>("passengerLng") ?: 0.0
                            val destLat = call.argument<Double>("destLat") ?: 0.0
                            val destLng = call.argument<Double>("destLng") ?: 0.0

                            val rideState =
                                    call.argument<String>("rideState")
                                            ?: "waiting" // "waiting" أو "inProgress"
                            val estimatedTime = call.argument<Int>("estimatedTime") ?: 5 // بالدقائق
                            val totalDistance =
                                    call.argument<Double>("totalDistance") ?: 0.0 // بالمتر

                            RideTrackingService.startOrUpdate(
                                    context = this,
                                    driverName = driverName,
                                    driverPhone = driverPhone,
                                    carDetails = carDetails,
                                    driverLat = driverLat,
                                    driverLng = driverLng,
                                    passengerLat = passengerLat,
                                    passengerLng = passengerLng,
                                    destLat = destLat,
                                    destLng = destLng,
                                    rideState = rideState,
                                    estimatedTime = estimatedTime,
                                    totalDistance = totalDistance
                            )

                            result.success(null)
                        }
                        "stopRideTracking" -> {
                            RideTrackingService.stop(this)
                            result.success(null)
                        }
                        else -> {
                            result.notImplemented()
                        }
                    }
                }
    }

    // ---------------- أمن الجهاز (كما عندك تقريباً) ----------------

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (isDeviceCompromised()) {
            showSecurityWarningDialog()
        }
    }

    private fun isDeviceCompromised(): Boolean {
        return try {
            nativeRootCheck() || rootBeerCheck() // || !safetyNetCheck()
        } catch (e: Exception) {
            Log.e("SecurityCheck", "Error during security checks: ${e.message}", e)
            true
        }
    }

    private fun nativeRootCheck(): Boolean {
        Log.d("SecurityCheck", "Starting native root detection...")
        return try {
            val isNativeRooted = RootDetection.isNativeRooted()
            Log.d("SecurityCheck", "Native root detection result: $isNativeRooted")
            isNativeRooted
        } catch (e: Exception) {
            Log.e("SecurityCheck", "Error in native root detection: ${e.message}", e)
            true
        }
    }

    private fun rootBeerCheck(): Boolean {
        Log.d("SecurityCheck", "Starting RootBeer root detection...")
        val rootBeer = RootBeer(this)
        val isRooted = rootBeer.isRooted
        Log.d("SecurityCheck", "RootBeer detection result: $isRooted")
        return isRooted
    }

    // SafetyNet (معلّق كما هو)
    private fun safetyNetCheck(): Boolean {
        Log.d("SecurityCheck", "Starting SafetyNet check...")
        var isSafe = false
        val semaphore = java.util.concurrent.Semaphore(0)

        SafetyNetCheck.checkSafetyNet(this, getString(R.string.api_key_safety)) { result ->
            isSafe = result
            Log.d("SecurityCheck", "SafetyNet check result: $isSafe")
            semaphore.release()
        }

        try {
            semaphore.acquire()
        } catch (e: InterruptedException) {
            Log.e("SecurityCheck", "Interrupted while waiting for SafetyNet check", e)
            return false
        }
        return isSafe
    }

    private fun showSecurityWarningDialog() {
        var secondsRemaining = 10

        val progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal)
        progressBar.max = 10
        progressBar.progress = 10

        val textView = TextView(this)
        textView.text = getString(R.string.security_warning_message)
        textView.textAlignment = TextView.TEXT_ALIGNMENT_CENTER

        val layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL
        layout.setPadding(48)
        layout.addView(textView)
        layout.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 {
            val packageName = applicationContext.packageName
            val runtime = Runtime.getRuntime()
            runtime.exec("pm clear $packageName")
        } catch (e: Exception) {
            clearCache()
            clearAppData()
        }

        finishAffinity()
        System.exit(0)
    }

    private fun clearCache() {
        try {
            deleteDir(cacheDir)
            deleteDir(externalCacheDir)
        } catch (e: Exception) {
            Log.e("SecurityCheck", "Error clearing cache: ${e.message}", e)
        }
    }

    private fun clearAppData() {
        try {
            deleteDir(applicationContext.dataDir)
        } catch (e: Exception) {
            Log.e("SecurityCheck", "Error clearing app data: ${e.message}", e)
        }
    }

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            val children = dir.list()
            if (children != null) {
                for (child in children) {
                    if (!deleteDir(File(dir, child))) {
                        return false
                    }
                }
            }
        }
        return dir?.delete() ?: false
    }
}
