package com.siro_driver.trip_overlay_plugin

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import org.json.JSONObject

/**
 * TripOverlayReceiver
 *
 * A BroadcastReceiver you can trigger directly from your FCM background handler (or anywhere
 * outside Flutter context) to show the overlay without needing an active MethodChannel.
 *
 * Usage from your backgroundMessageHandler in main.dart: — Call the static helper
 * [TripOverlayReceiver.show(context, tripDataJson)]
 *
 * Or register in AndroidManifest and send an explicit broadcast.
 *
 * Register in AndroidManifest.xml: <receiver
 * ```
 *       android:name="com.trip_overlay.TripOverlayReceiver"
 *       android:exported="false" />
 * ```
 */
class TripOverlayReceiver : BroadcastReceiver() {

    companion object {
        const val TAG = "TripOverlayReceiver"
        const val ACTION = "com.siro_driver.SHOW_OVERLAY"
        const val EXTRA_TRIP_DATA = "trip_data"
        const val EXTRA_AUTO_CLOSE = "auto_close_seconds"

        /**
         * Convenience method — call this from your FCM handler (Kotlin/Java) or from a Flutter
         * MethodChannel invocation.
         */
        fun show(context: Context, tripDataJson: String, autoCloseSeconds: Int = 30) {
            val intent =
                    Intent(context, TripOverlayService::class.java).apply {
                        action = TripOverlayService.ACTION_SHOW
                        putExtra(TripOverlayService.EXTRA_TRIP_DATA, tripDataJson)
                        putExtra(TripOverlayService.EXTRA_AUTO_CLOSE_SECONDS, autoCloseSeconds)
                    }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
            Log.d(TAG, "Dispatched show overlay request")
        }

        /** Hide the overlay programmatically from native side */
        fun hide(context: Context) {
            val intent =
                    Intent(context, TripOverlayService::class.java).apply {
                        action = TripOverlayService.ACTION_HIDE
                    }
            context.startService(intent)
            Log.d(TAG, "Dispatched hide overlay request")
        }

        /**
         * Build a TripData JSON string from FCM message data map. Keys match what your server sends
         * inside the FCM data payload.
         *
         * Expected FCM data keys: tripId, passengerName, pickupAddress, dropoffAddress, distanceKm,
         * estimatedFare, estimatedMinutes, pickupLat, pickupLng
         */
        fun buildTripJsonFromFcmData(data: Map<String, String>): String {
            return try {
                JSONObject()
                        .apply {
                            put("tripId", data["tripId"] ?: "")
                            put("passengerName", data["passengerName"] ?: "غير معروف")
                            put("pickupAddress", data["pickupAddress"] ?: "")
                            put("dropoffAddress", data["dropoffAddress"] ?: "")
                            put("distanceKm", data["distanceKm"]?.toDoubleOrNull() ?: 0.0)
                            put("estimatedFare", data["estimatedFare"]?.toDoubleOrNull() ?: 0.0)
                            put("estimatedMinutes", data["estimatedMinutes"]?.toIntOrNull() ?: 0)
                            put("pickupLat", data["pickupLat"]?.toDoubleOrNull() ?: 0.0)
                            put("pickupLng", data["pickupLng"]?.toDoubleOrNull() ?: 0.0)
                            put("passengerAvatarUrl", data["passengerAvatarUrl"] ?: "")
                        }
                        .toString()
            } catch (e: Exception) {
                Log.e(TAG, "Error building trip JSON: ${e.message}")
                "{}"
            }
        }
    }

    // ─── Broadcast received ───────────────────────────────────────────────────

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != ACTION) return

        val tripData =
                intent.getStringExtra(EXTRA_TRIP_DATA)
                        ?: run {
                            Log.e(TAG, "No trip data in broadcast intent")
                            return
                        }
        val autoClose = intent.getIntExtra(EXTRA_AUTO_CLOSE, 30)
        show(context, tripData, autoClose)
        Log.d(TAG, "Received broadcast, showing overlay")
    }
}
