// package com.performics

// import android.app.Activity
// import android.content.Intent
// import android.util.Log
// import com.cpm.india.cameraai.camera.CameraActivity
// import com.facebook.react.bridge.*
// import java.io.File
// import androidx.activity.result.ActivityResultLauncher
// import androidx.activity.result.contract.ActivityResultContracts

// class CameraaiModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

//     private var cameraPromise: Promise? = null
//     private var cameraLauncher: ActivityResultLauncher<Intent>? = null

//     init {
//         setupCameraLauncher()
//     }

//     private fun setupCameraLauncher() {
//         val activity = getCurrentActivity()
//         if (activity is androidx.activity.ComponentActivity && cameraLauncher == null) {
//             cameraLauncher = activity.registerForActivityResult(
//                 ActivityResultContracts.StartActivityForResult()
//             ) { result ->
//                 if (result.resultCode == Activity.RESULT_OK && result.data != null) {
//                     val photoPath = result.data!!.getStringExtra("filePath")
//                     cameraPromise?.resolve(photoPath)
//                 } else {
//                     cameraPromise?.reject("CAMERA_CANCELLED", "Camera was cancelled")
//                 }
//                 cameraPromise = null
//             }
//         }
//     }

//     override fun getName(): String = "CameraaiModule"

//     @ReactMethod
//     fun initializeSDK(options: ReadableMap, promise: Promise) {
//         try {
//             val filePath = options.getString("filePath")
//                 ?: throw IllegalArgumentException("filePath is required")

//             val photoFile = File(filePath)
//             this.cameraPromise = promise

//             val activity = getCurrentActivity()
//             if (activity == null) {
//                 promise.reject("NO_ACTIVITY", "Activity not available")
//                 return
//             }

//             if (cameraLauncher == null) setupCameraLauncher()

//             val intent = Intent(activity, CameraActivity::class.java).apply {
//                 putExtra("filePath", photoFile.absolutePath)
//                 putExtra("isGrid", false)
//                 putExtra("isFacingFront", true)
//                 putExtra("isCheckFace", true)
//             }

//             cameraLauncher?.launch(intent)
//                 ?: promise.reject("LAUNCHER_ERROR", "Launcher not ready")

//         } catch (e: Exception) {
//             Log.e("CameraaiModule", "Error: ${e.message}", e)
//             cameraPromise?.reject("ERROR", e.message ?: "Unknown", e)
//         }
//     }

//     override fun onCatalystInstanceDestroy() {
//         cameraLauncher?.unregister()
//         cameraLauncher = null
//         super.onCatalystInstanceDestroy()
//     }
// }


package com.performics

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import com.cpm.india.cameraai.camera.CameraActivity
import com.facebook.react.bridge.*

import java.io.File

class CameraaiModule(private val reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext), ActivityEventListener {

    private var cameraPromise: Promise? = null
    private val CAMERA_REQUEST_CODE = 1001

    init {
        // Register to receive Activity results
        reactContext.addActivityEventListener(this)
    }

    override fun getName(): String = "CameraaiModule"

    @ReactMethod
    fun initializeSDK(options: ReadableMap, promise: Promise) {
        try {
            val filePath = options.getString("filePath")
                ?: throw IllegalArgumentException("filePath is required")

            val photoFile = File(filePath)
            cameraPromise = promise

            // ✅ Get Activity from reactContext
            val activity: Activity? = reactContext.currentActivity
            if (activity == null) {
                promise.reject("NO_ACTIVITY", "Activity not available")
                cameraPromise = null
                return
            }

            // Create intent to launch CameraActivity
            val intent = Intent(activity as Context, CameraActivity::class.java).apply {
                putExtra("filePath", photoFile.absolutePath)
                putExtra("isGrid", false)
                putExtra("isFacingFront", true)
                putExtra("isCheckFace", true)
            }

            activity.startActivityForResult(intent, CAMERA_REQUEST_CODE)

        } catch (e: Exception) {
            Log.e("CameraaiModule", "Error in initializeSDK: ${e.message}", e)
            cameraPromise?.reject("ERROR", e.message ?: "Unknown error", e)
            cameraPromise = null
        }
    }

    override fun onActivityResult(
        activity: Activity,
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        if (requestCode != CAMERA_REQUEST_CODE || cameraPromise == null) return

        if (resultCode == Activity.RESULT_OK && data != null) {
            val photoPath = data.getStringExtra("filePath")
            if (photoPath != null) {
                cameraPromise?.resolve(photoPath)
            } else {
                cameraPromise?.reject("NO_FILEPATH", "No filePath returned from CameraActivity")
            }
        } else {
            cameraPromise?.reject(
                "CAMERA_CANCELLED",
                "Camera was cancelled or failed (resultCode = $resultCode)"
            )
        }

        cameraPromise = null
    }

    override fun onNewIntent(intent: Intent) {
        // Not used, but must be implemented
    }

    override fun onCatalystInstanceDestroy() {
        cameraPromise = null
        super.onCatalystInstanceDestroy()
    }
}
