import UIKit
import React
import WebEngage
import WENotificationInbox

@objc(WEInboxBridge)
class WEInboxBridge: RCTEventEmitter {
    
    let wegNIVersion = "1.0.4"
    
    override init() {
        super.init()
        WENotificationInbox.initialize()
    }
    
    // Version Tracking
    func initializeWEGVersion() {
        let key: WegVersionKey = .RNNI
        WebEngage.sharedInstance().setVersionForChildSDK(wegNIVersion, for: key)
    }

    @objc func initWENotificationInbox() {
        initializeWEGVersion()
    }
    
    // Response Handling - Notification List
    func handleNotificationListSuccess(response: WEInboxData, _ callback: @escaping RCTResponseSenderBlock) {
        let messageList = response.messageList
        let jsonArray = messageList.map { $0.jsonData }
        let jsonString = convertToJsonString(jsonArray: jsonArray)
        let apiResponse: [String: Any] = ["hasNext": response.hasNextPage, "messageList": jsonString]
        callback([apiResponse, NSNull()])
        
    }
    
    func handleNotificationError(error: WEInboxError, _ callback: @escaping RCTResponseSenderBlock) {
        let errorMap: [String: Any] = [
            "error": [
                "response": [
                    "status": error.status,
                    "message": error.localizedDescription
                ]
            ]
        ]
        callback([NSNull(), errorMap])
    }
    
    func handleNotificationCountError(error: WEInboxError, _ callback: @escaping RCTResponseSenderBlock) {
        let errorMap: [String: Any] = [
            "error": [
                "response": [
                    "status": error.status,
                    "message": error.localizedDescription
                ]
            ]
        ]
        callback([NSNull(), errorMap])
    }
    
    //  API Methods
    @objc func onNotificationIconClick() {
        WENotificationInbox.shared.onNotificationIconClick()
    }
    
    @objc func getNotificationCount(_ callback: @escaping RCTResponseSenderBlock) {
        WENotificationInbox.shared.getUserNotificationCount { data, error in
            if let count = data {
                callback([count, NSNull()])
            } else {
                if let errorMap = error {
                    self.handleNotificationError(error: errorMap, callback)
                }
            }
        }
    }
    
    
    @objc func getNotificationList(_ offsetJSON: String? = nil, callback: @escaping RCTResponseSenderBlock) {
            var lastInboxMessage: WEInboxMessage? = nil
            if let offset = offsetJSON, let jsonData = offset.data(using: .utf8) {
                do {
                    if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                        lastInboxMessage = WEInboxMessage(param: json)
                    } else {
                        print("WebEngage-Inbox: Invalid offset JSON")
                    }
                } catch {
                    print("WebEngage-Inbox: Error parsing JSON - \(error)")
                }
            }
            
            WENotificationInbox.shared.getNotificationList(lastInboxData: lastInboxMessage) { response, error in
                if let response = response {
                    self.handleNotificationListSuccess(response: response, callback)
                } else if let error = error {
                    self.handleNotificationError(error: error, callback)
                }
            }
        }
    
    // Utility Methods
    func convertToJsonString(jsonArray: Any) -> String {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonArray, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            }
        } catch {
            print("WebEngage-Inbox: Error converting messageListData to JSON: \(error)")
        }
        return ""
    }
    
    @objc func markRead(_ readMap: NSDictionary) {
        WENIHelper.shared.handleInboxEvent(event_name: "markRead", map: readMap)
    }
    
    @objc func markUnread(_ readMap: NSDictionary) {
        WENIHelper.shared.handleInboxEvent(event_name: "markUnread", map: readMap)
        
    }
    
    @objc func trackClick(_ readMap: NSDictionary) {
        WENIHelper.shared.handleInboxEvent(event_name: "trackClick", map: readMap)
        
    }
    
    @objc func trackView(_ readMap: NSDictionary) {
        WENIHelper.shared.handleInboxEvent(event_name: "trackView", map: readMap)
    }
    
    
    @objc func markDelete(_ readMap: NSDictionary) {
        WENIHelper.shared.handleInboxEvent(event_name: "markDelete", map: readMap)
    }
    
    
    
    @objc func readAll(_ notificationList: NSArray) {
        WENIHelper.shared.handleMultipleInboxEvent(event_name: "markRead", notificationList: notificationList)
    }
    
    
    @objc func unReadAll(_ notificationList: NSArray) {
        WENIHelper.shared.handleMultipleInboxEvent(event_name: "markUnread", notificationList: notificationList)
    }
    
    
    @objc func deleteAll(_ notificationList: NSArray) {
        WENIHelper.shared.handleMultipleInboxEvent(event_name: "markDelete", notificationList: notificationList)
    }
    
    
    // React Native Overrides
    
    override class func requiresMainQueueSetup() -> Bool {
        return false
    }
    
    
    override func supportedEvents() -> [String] {
        ["notificationList", "notificationCount"]
    }
    
}
