#if os(iOS)
import BackgroundTasks
import Foundation
import React
import demo_address_verification_ios

@objc(SIDAddressVerification)
class SIDAddressVerification: RCTEventEmitter {
    
    @objc
    static override func requiresMainQueueSetup() -> Bool {
        return true
    }
    
    override func supportedEvents() -> [String]! {
        return ["onLocationUpdate"]
    }
    
    @objc
    func multiply(
        _ a: Double,
        b: Double,
        resolve: @escaping RCTPromiseResolveBlock,
        reject: @escaping RCTPromiseRejectBlock
    ) {
        let result = a * b
        resolve(result)
    }
    
    @objc
    func fetchConfiguration(
        _ apiKey: String,
        customerID: String,
        token: String,
        refreshToken: String,
        resolve: @escaping RCTPromiseResolveBlock,
        reject: @escaping RCTPromiseRejectBlock
    ) {
        Task {
            do {
                let (pollingInterval, sessionTimeout) = try await fetchRemoteConfiguration(
                    apiKey: apiKey,
                    customerID: customerID
                    // token: token,
                    // refreshToken: refreshToken
                )
                
                let result: [String: Any] = [
                    "pollingInterval": pollingInterval,
                    "sessionTimeout": sessionTimeout
                ]
                
                DispatchQueue.main.async {
                    resolve(result)
                }
            } catch {
                DispatchQueue.main.async {
                    reject("CONFIG_ERROR", "Failed to fetch configuration: \(error.localizedDescription)", error)
                }
            }
        }
    }
    
    @objc
    func startTrackingWithConfig(
        _ apiKey: String,
      customerID: String,
      verificationId: String,
        resolve: @escaping RCTPromiseResolveBlock,
        reject: @escaping RCTPromiseRejectBlock
    ) {
        AddressVerificationField.startTrackingWithRemoteConfig(
            apiKey: apiKey,
            customerID: customerID,
            verificationGroupId: verificationId,
            onLocationPost: { [weak self] lat, long in
                print("Posted location: \(lat), \(long)")
                
                // Send location update to React Native
                let locationData: [String: Any] = [
                    "latitude": lat,
                    "longitude": long,
                    "timestamp": Date().timeIntervalSince1970
                ]
                
                DispatchQueue.main.async {
                    self?.sendEvent(withName: "onLocationUpdate", body: locationData)
                }
            }
        )
        
        DispatchQueue.main.async {
            resolve(true)
        }
    }
    
    @objc
    func stopTracking() {
        // Add your stop tracking logic here if available in AddressVerificationField
        // AddressVerificationField.stopTracking()
        print("Stopping tracking...")
    }
    
    @objc
    override func addListener(_ eventName: String) {
        // Required for RCTEventEmitter
    }
    
    @objc
    override func removeListeners(_ count: Double) {
        // Required for RCTEventEmitter
    }
    
    private func fetchRemoteConfiguration(
        apiKey: String,
        customerID: String
        // token: String,
        // refreshToken: String
    ) async throws -> (TimeInterval, TimeInterval) {
        let config = try await AddressVerificationField.fetchConfigFromServer(
            apiKey: apiKey,
            customerID: customerID
            // token: token,
            // refreshToken: refreshToken
        )
        return (config.pollingInterval, config.sessionTimeout)
    }
    
    @objc
    static func handleBackgroundGeotagTask(_ task: BGProcessingTask) {
        // Forward to your AddressVerification package if needed
    }
@objc
func pickLocation(
    _ resolve: @escaping RCTPromiseResolveBlock,
    reject: @escaping RCTPromiseRejectBlock
) {
    DispatchQueue.main.async {
        // Get the root view controller
        guard let rootViewController = self.getRootViewController() else {
            reject("NO_VIEW_CONTROLLER", "Cannot find root view controller", nil)
            return
        }
        
        // Call the SDK's pickLocation method
        AddressVerification.shared.pickLocation(from: rootViewController) { resolvedAddress in
            // Return the complete address to React Native
            let result: [String: Any] = [
                "latitude": resolvedAddress.latitude,
                "longitude": resolvedAddress.longitude,
                "fullAddress": resolvedAddress.fullAddress,
                "country": resolvedAddress.country as Any,
                "state": resolvedAddress.state as Any,
                "city": resolvedAddress.city as Any,
                "postalCode": resolvedAddress.postalCode as Any,
                "street": resolvedAddress.street as Any
            ]
            resolve(result)
        }
    }
}
    
    // MARK: - Helper to get Root View Controller
    private func getRootViewController() -> UIViewController? {
        guard let window = UIApplication.shared.keyWindow ?? UIApplication.shared.windows.first else {
            return nil
        }
        
        var rootViewController = window.rootViewController
        
        // Handle presented view controllers
        while let presentedVC = rootViewController?.presentedViewController {
            rootViewController = presentedVC
        }
        
        return rootViewController
    }
    

}

#endif