import Foundation
import FLAnimatedImage


var flutterMethodChannelPenguinIn:FlutterMethodChannel? = nil
fileprivate var mainViewController:MainFlutterVC!

class HMGPenguinInPlatformBridge{
    
    private let channelName = "launch_penguin_ui"
    private static var shared_:HMGPenguinInPlatformBridge?
    
    class func initialize(flutterViewController:MainFlutterVC){
        shared_ = HMGPenguinInPlatformBridge()
        mainViewController = flutterViewController
        shared_?.openChannel()
    }
    
    func shared() -> HMGPenguinInPlatformBridge{
        assert((HMGPenguinInPlatformBridge.shared_ != nil), "HMGPenguinInPlatformBridge is not initialized, call initialize(mainViewController:MainFlutterVC) function first.")
        return HMGPenguinInPlatformBridge.shared_!
    }
    
    private func openChannel(){
        flutterMethodChannelPenguinIn = FlutterMethodChannel(name: channelName, binaryMessenger: mainViewController.binaryMessenger)
        
        flutterMethodChannelPenguinIn?.setMethodCallHandler { (methodCall, result) in
            print("Called function \(methodCall.method)")
            
            if let arguments = methodCall.arguments as Any? {
                if methodCall.method == "launchPenguin"{
                  print("====== launchPenguinView Launched =========")
                    self.launchPenguinView(arguments: arguments, result: result)
                }
            } else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Storyboard name is required", details: nil))
            }
        }
    }

    private func launchPenguinView(arguments: Any, result: @escaping FlutterResult) {
   
        let penguinView = PenguinView(
            frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height),
            viewIdentifier: 0,
            arguments: arguments,
            binaryMessenger: mainViewController.binaryMessenger
        )
        
        let penguinUIView = penguinView.view()
        penguinUIView.frame = mainViewController.view.bounds
        penguinUIView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
      
        mainViewController.view.addSubview(penguinUIView)
        
        guard let args = arguments as? [String: Any],
                let loaderImageData = args["loaderImage"] as? FlutterStandardTypedData else {
              print("loaderImage data not found in arguments")
              result(FlutterError(code: "ARGUMENT_ERROR", message: "Missing loaderImage data", details: nil))
              return
          }

        let loadingOverlay = UIView(frame: UIScreen.main.bounds)
        loadingOverlay.backgroundColor = UIColor.black.withAlphaComponent(0.5) // Semi-transparent overlay
        loadingOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        // Display the GIF using FLAnimatedImage
        let animatedImage = FLAnimatedImage(animatedGIFData: loaderImageData.data)
        let gifImageView = FLAnimatedImageView()
        gifImageView.animatedImage = animatedImage
        gifImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        gifImageView.center = loadingOverlay.center
        gifImageView.contentMode = .scaleAspectFit
        loadingOverlay.addSubview(gifImageView)
        
        
        if let window = UIApplication.shared.windows.first {
                window.addSubview(loadingOverlay)
            
           } else {
               print("Error: Main window not found")
           }
        
           penguinView.onSuccess = {
               // Hide and remove the loader
               DispatchQueue.main.async {
                   loadingOverlay.removeFromSuperview()
                 
               }
           }

        result(nil)
    }
}
