//
//  TestUiInteractor.swift
//  AirbridgeQA
//
//  Created by ab180 on 3/31/25.
//
import UIKit
import React
import Foundation
import AirbridgeQALibrary

@objc(TestUiInteractor)
class TestUiInteractor: NSObject {
  
  @objc
  static func requiresMainQueueSetup() -> Bool {
    return true
  }
  
  @objc(purchase)
  func purchase() {
    let vc = InAppPurchaseViewController()
    WindowPresenter.show(viewController: vc)
  }
  
  @objc(consentData)
  func consentData() {
    let uiStoryboard = UIStoryboard(
      name: "Application",
      bundle: Bundle(identifier: "co.ab180.airbridge.qa.library")
    )
    
    let vc = uiStoryboard.instantiateViewController(identifier: "DMAController")
    WindowPresenter.show(viewController: vc)
  }
}

enum WindowPresenter {
  static var window: UIWindow = UIWindow()
  static var context: Context? = nil
  
  static func show(viewController: UIViewController) {
    DispatchQueue.main.async {
      window.frame = UIScreen.main.bounds
      window.rootViewController = UIViewController()
      window.windowLevel = .alert + 1
      window.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
      
      window.makeKeyAndVisible()
      
      let navigationController = UINavigationController()
      let homeAction = HomeAction {
        navigationController.dismiss(animated: true) {
          window.isHidden = true
          context = nil
        }
      }
      
      context = Context(
        homeAction: homeAction,
        navigationController: navigationController,
        viewController: viewController
      )
      
      navigationController.pushViewController(viewController, animated: true)
      
      navigationController.modalPresentationStyle = .fullScreen
      window.rootViewController?.present(navigationController, animated: true) {
        viewController.navigationItem.rightBarButtonItems = [
          {
            let button = UIBarButtonItem(
              title: "Home",
              style: .plain,
              target: homeAction,
              action: #selector(HomeAction.execute)
            )
            button.accessibilityIdentifier = "navigateHome"
            return button
          }(),
        ]
      }
    }
  }
  
  struct Context {
    let homeAction: HomeAction
    let navigationController: UINavigationController
    let viewController: UIViewController
  }
  
  class HomeAction {
    let block: () -> Void
    
    init(block: @escaping () -> Void) {
      self.block = block
    }
    
    @objc
    func execute() {
      block()
    }
  }
}
