package com.eventtan.app.penguin_flutter_sample.penguin

import android.app.Activity
import android.content.Context
import android.content.Context.RECEIVER_EXPORTED
import android.content.IntentFilter
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.eventtan.test.penguin_flutter_sample.MainActivity
import com.eventtan.test.penguin_flutter_sample.PermissionManager.PermissionHelper
import com.eventtan.test.penguin_flutter_sample.PermissionManager.PermissionManager
import com.eventtan.test.penguin_flutter_sample.PermissionManager.PermissionResultReceiver
import com.peng.pennavmap.PlugAndPlayConfiguration
import com.peng.pennavmap.PlugAndPlaySDK
import com.peng.pennavmap.enums.InitializationErrorType
import com.peng.pennavmap.interfaces.PenNavUIDelegate
import com.peng.pennavmap.utils.Languages
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

/**
 * Custom PlatformView for displaying Penguin UI components within a Flutter app.
 * Implements `PlatformView` for rendering the view, `MethodChannel.MethodCallHandler` for handling method calls,
 * and `PenNavUIDelegate` for handling SDK events.
 */
@RequiresApi(Build.VERSION_CODES.O)
internal class PenguinView(
    context: Context,
    id: Int,
    val creationParams: Map<String, String>,
    messenger: BinaryMessenger,
    activity: MainActivity
) : PlatformView, MethodChannel.MethodCallHandler, PenNavUIDelegate {
    // The layout for displaying the Penguin UI
    private val mapLayout: RelativeLayout = RelativeLayout(context)
    private val _context: Context = context

    private val permissionResultReceiver: PermissionResultReceiver
    private val permissionIntentFilter = IntentFilter("PERMISSION_RESULT_ACTION")

    private companion object {
        const val PERMISSIONS_REQUEST_CODE = 1
    }

    private lateinit var permissionManager: PermissionManager

    // Reference to the main activity
    private var _activity: Activity = activity

    private lateinit var mContext: Context

    init {
        // Set layout parameters for the mapLayout
        mapLayout.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )

        mContext = (_activity as MainActivity).context


        permissionResultReceiver = PermissionResultReceiver { granted ->
            if (granted) {
                onPermissionsGranted()
            } else {
                onPermissionsDenied()
            }
        }
//todo handle properly the way it in the main app check the sdk version and cal it appropiately
        mContext.registerReceiver(permissionResultReceiver, permissionIntentFilter,RECEIVER_EXPORTED)

        // Set the background color of the layout
        mapLayout.setBackgroundColor(Color.RED)

        permissionManager = PermissionManager(
            context = mContext,
            listener = object : PermissionManager.PermissionListener {
                override fun onPermissionGranted() {
                    // Handle permissions granted
                    onPermissionsGranted()
                }

                override fun onPermissionDenied() {
                    // Handle permissions denied
                    onPermissionsDenied()
                }
            },
            requestCode = PERMISSIONS_REQUEST_CODE,
            *PermissionHelper.getRequiredPermissions()
        )

        if (!permissionManager.arePermissionsGranted()) {
            permissionManager.requestPermissions(_activity)
        } else {
            // Permissions already granted
            permissionManager.listener.onPermissionGranted()
        }



    }

    private fun onPermissionsGranted() {
        // Handle the actions when permissions are granted
        Log.d("PermissionsResult", "onPermissionsGranted")
        // Register the platform view factory for creating custom views

        // Initialize the Penguin SDK
        initPenguin()



    }

    private fun onPermissionsDenied() {
        // Handle the actions when permissions are denied
        Log.d("PermissionsResult", "onPermissionsDenied")

    }

    /**
     * Returns the view associated with this PlatformView.
     *
     * @return The main view for this PlatformView.
     */
    override fun getView(): View {
        return mapLayout
    }

    /**
     * Cleans up resources associated with this PlatformView.
     */
    override fun dispose() {
        // Cleanup code if needed
    }

    /**
     * Handles method calls from Dart code.
     *
     * @param call The method call from Dart.
     * @param result The result callback to send responses back to Dart.
     */
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        // Handle method calls from Dart code here
    }

    /**
     * Initializes the Penguin SDK with custom configuration and delegates.
     */
    private fun initPenguin() {
        // Configure the PlugAndPlaySDK
        PlugAndPlaySDK.configuration = PlugAndPlayConfiguration.Builder()
            .setBaseUrl(creationParams["baseURL"], creationParams["positionURL"])
            .setServiceName(creationParams["dataServiceName"], creationParams["positionServiceName"])
            .setClientData(creationParams["clientID"], creationParams["clientKey"])
            .setUserName("client")
            .setLanguageID(Languages.en)
            .setSimulationModeEnabled(false)
            .setEnableBackButton(true)
            .setDeepLinkData("deeplink")
            .setCustomizeColor("#2CA0AF")
            .setDeepLinkSchema("")
            .setDeepLinkData(null)
            .build()

        // Set location delegate to handle location updates
        PlugAndPlaySDK.setPiLocationDelegate {
            // Example code to handle location updates
            // Uncomment and modify as needed
            // if (location.size() > 0)
            //     Toast.makeText(_context, "Location Info Latitude: ${location[0]}, Longitude: ${location[1]}", Toast.LENGTH_SHORT).show()
        }

        // Set events delegate for reporting issues
        PlugAndPlaySDK.setPiEventsDelegate { }

        // Start the Penguin SDK
        PlugAndPlaySDK.start(mContext, this)
    }

    /**
     * Called when Penguin UI setup is successful.
     *
     * @param warningCode Optional warning code received from the SDK.
     */
    override fun onPenNavSuccess(warningCode: String?) {
//        if (_context is Activity) {
//            _context.runOnUiThread {
//                Toast.makeText(_context, "Success Info: $warningCode", Toast.LENGTH_SHORT).show()
//            }
//        } else {
//            println("the warming is presented $$warningCode")
////            val handler = Handler(Looper.getMainLooper())
////            handler.post {
////                Toast.makeText(_context, "Success Info: $warningCode", Toast.LENGTH_SHORT).show()
////            }
//        }
    }

    /**
     * Called when there is an initialization error with Penguin UI.
     *
     * @param description Description of the error.
     * @param errorType Type of initialization error.
     */
    override fun onPenNavInitializationError(
        description: String?,
        errorType: InitializationErrorType?
    ) {
        Toast.makeText(mContext, "Navigation Error: $description", Toast.LENGTH_SHORT).show()
    }

    /**
     * Called when Penguin UI is dismissed.
     */
    override fun onPenNavUIDismiss() {
        // Handle UI dismissal if needed
        try {
            mContext.unregisterReceiver(permissionResultReceiver)
            dispose();
        } catch (e: IllegalArgumentException) {
            Log.e("PenguinView", "Receiver not registered: $e")
        }
    }
}

