import { action, makeObservable, observable } from 'mobx';
import { TaskState } from '@wix/bex-core';

export interface LoadingRow {
  id: string;
  startTime: number;
}

export class LoadingRowState {
  readonly loadingItems = observable.map<string, LoadingRow>([], {
    deep: false,
  });
  animationDuration = 2000;
  animationData = undefined as { layers: any[] } | undefined;
  LottieRenderer = undefined as
    | typeof import('lottie-react').default
    | undefined;

  loadAnimationAssetsTask = new TaskState();

  constructor() {
    makeObservable(this, {
      animationData: observable.ref,
      LottieRenderer: observable.ref,
      addLoadingItem: action,
      removeLoadingItem: action,
    });
  }

  addLoadingItem(id: string) {
    this._loadAnimationAssets();
    this.loadingItems.set(id, {
      id,
      startTime: Date.now(),
    });

    window.setTimeout(() => {
      this.removeLoadingItem(id);
    }, this.animationDuration);
  }

  removeLoadingItem(id: string) {
    this.loadingItems.delete(id);
  }

  isLoading(id: string): boolean {
    return this.loadingItems.has(id);
  }

  async setLottieRenderer() {
    this.LottieRenderer = (await import('lottie-react')).default;
  }

  async setAnimationData() {
    this.animationData = (await import('./aiLoadingLottie')).aiLoadingLottie;
  }

  _loadAnimationAssets() {
    this.loadAnimationAssetsTask.runOnce(async () => {
      await Promise.all([this.setLottieRenderer(), this.setAnimationData()]);
    });
  }
}
