//
//  MessagesViewController.swift
//  GIFCollector MessagesExtension
//
//  Created by Joshua Higgins on 6/2/25.
//

import Messages
import UIKit

class MessagesViewController: MSMessagesAppViewController {

  private var gifCollectionVC: GIFCollectionViewController?

  override func viewDidLoad() {
    super.viewDidLoad()
    setupChildViewController()
    
    // Register for notifications when app becomes active
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(appDidBecomeActive),
                                           name: UIApplication.didBecomeActiveNotification,
                                           object: nil)
  }

  private func setupChildViewController() {
    let collectionVC = GIFCollectionViewController()
    collectionVC.onSelectGIF = { [weak self] gif in
      self?.sendGIF(gif)
    }

    addChild(collectionVC)
    collectionVC.view.frame = view.bounds
    collectionVC.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    view.addSubview(collectionVC.view)
    collectionVC.didMove(toParent: self)

    gifCollectionVC = collectionVC
  }

  private func sendGIF(_ gif: GIF) {
      guard let conversation = activeConversation else { return }
        
      // Show a loading indicator
      let loadingAlert = UIAlertController(title: "Preparing GIF", message: "Please wait...", preferredStyle: .alert)
      present(loadingAlert, animated: true)
        
      // Load the GIF data from local storage
      DispatchQueue.global(qos: .userInitiated).async {
          let gifData = GIFStorageService.shared.getGIFData(for: gif)
            
          DispatchQueue.main.async {
              // Dismiss the loading indicator
              self.dismiss(animated: true) {
                  guard let gifData = gifData else {
                      self.showErrorAlert(message: "Failed to load GIF from storage")
                      return
                  }
                    
                  // Create a temporary file URL for the GIF
                  let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                  let tempFileURL = tempDirectoryURL.appendingPathComponent(UUID().uuidString).appendingPathExtension("gif")
                    
                  do {
                      // Write GIF data to temporary file
                      try gifData.write(to: tempFileURL)
                        
                      // Insert the GIF directly as a standard attachment into the message field
                      conversation.insertAttachment(tempFileURL, withAlternateFilename: "animated.gif") { error in
                          if let error = error {
                              self.showErrorAlert(error: error)
                          } else {
                              // Successfully inserted the attachment
                              self.requestPresentationStyle(.compact)
                          }
                      }
                  } catch {
                      self.showErrorAlert(error: error)
                  }
              }
          }
      }
  }

  private func showErrorAlert(error: Error? = nil, message: String? = nil) {
    let errorMessage = message ?? error?.localizedDescription ?? "An unknown error occurred"
    let alertController = UIAlertController(
      title: "Error", message: errorMessage, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .default))
    present(alertController, animated: true)
  }

  // MARK: - Conversation Handling

  override func willBecomeActive(with conversation: MSConversation) {
    // Called when the extension is about to move from the inactive to active state.
    // This will happen when the extension is about to present UI.

    // Check for GIFs shared from the Share Extension
    GIFStorageService.shared.checkForSharedGIFs()
    
    // Refresh GIFs list when becoming active
    gifCollectionVC?.viewWillAppear(true)
  }

  override func didResignActive(with conversation: MSConversation) {
    // No action needed when the extension becomes inactive
  }
  
  @objc private func appDidBecomeActive() {
    // Check for GIFs shared through the Share Extension
    GIFStorageService.shared.checkForSharedGIFs()
    gifCollectionVC?.loadGIFs()
  }
  override func didReceive(_ message: MSMessage, conversation: MSConversation) {}
  override func didStartSending(_ message: MSMessage, conversation: MSConversation) {}
  override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {}
  override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {}
  override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {}
}
