//
//  LottieView.swift
//  MoMoPlatform
//
//  Created by thanhdat on 16/01/2023.
//  Copyright © 2023 Facebook. All rights reserved.
//

import SwiftUI
import Lottie

struct LottieView: UIViewRepresentable {
  var name: String = ""
  var url: String?
  var loopMode: LottieLoopMode = .playOnce
  var contentMode : UIView.ContentMode  = .scaleAspectFit
  var onDone: (() -> Void)?

  // Add static cache for animations
  private static var animationCache = NSCache<NSString, LottieAnimation>()

  func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
    let view = UIView(frame: .zero)

    // Configure Lottie with optimized settings
    let configuration = LottieConfiguration(
      renderingEngine: .coreAnimation,
      decodingStrategy: .dictionaryBased
    )

    let animationView = LottieAnimationView(configuration: configuration)

    if let url = url {
      // Use cached animation if available
      if let cachedAnimation = Self.animationCache.object(forKey: url as NSString) {
        animationView.animation = cachedAnimation
        setupAnimationView(animationView, view)
      } else {
        LottieAnimation.loadedFrom(url: URL(string: url)!, closure: { animation in
          if let animation = animation {
            Self.animationCache.setObject(animation, forKey: url as NSString)
            animationView.animation = animation
            setupAnimationView(animationView, view)
          }
        }, animationCache: nil)
      }
    } else {
      // Use cached animation if available
      if let cachedAnimation = Self.animationCache.object(forKey: name as NSString) {
        animationView.animation = cachedAnimation
        setupAnimationView(animationView, view)
      } else if let animation = LottieAnimation.named(name) {
        Self.animationCache.setObject(animation, forKey: name as NSString)
        animationView.animation = animation
        setupAnimationView(animationView, view)
      }
    }

    return view
  }

  private func setupAnimationView(_ animationView: LottieAnimationView, _ containerView: UIView) {
    animationView.contentMode = contentMode
    animationView.loopMode = loopMode
    animationView.backgroundBehavior = loopMode == .loop ? .pauseAndRestore : .pause

    // Optimize rendering
    animationView.shouldRasterizeWhenIdle = true

    animationView.translatesAutoresizingMaskIntoConstraints = false
    containerView.addSubview(animationView)

    NSLayoutConstraint.activate([
      animationView.widthAnchor.constraint(equalTo: containerView.widthAnchor),
      animationView.heightAnchor.constraint(equalTo: containerView.heightAnchor)
    ])

    animationView.play { finished in
      if finished {
        onDone?()
      }
    }
  }

  func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {}
}
