import { ImportParams, PrimariaImportDataManager } from "./import-data-manager";
import { PrimariaInteractionService } from "../interaction-service/interaction-service";

export class ImportDataManagerImpl implements PrimariaImportDataManager {
  private selectedItems: Record<string, any[]> = {};
  private currentImporterId = "";
  private currentImportParams: ImportParams | undefined;
  private pluginTexts: Record<string, { raw: string; html: string }> = {};

  constructor(private interactionService: PrimariaInteractionService) {}

  async import(
    importerId: string,
    params?: ImportParams,
  ): Promise<{
    accepted: boolean;
    data: Record<string, any[]>;
    text: { raw: string; html: string };
  }> {
    this.currentImporterId = importerId;
    this.currentImportParams = params;
    this.selectedItems = {};
    this.pluginTexts = {};

    try {
      // Import component dynamically to avoid circular dependency
      const { ImportDataManagerModal } = await import("./component/component");

      const { confirmed } = await this.interactionService.confirm(
        undefined,
        { component: ImportDataManagerModal as any },
        {
          fullCustomization: true,
        },
      );

      const concatenatedText = this.getConcatenatedText();

      const finalResult = {
        accepted: confirmed,
        data: confirmed ? this.selectedItems : {},
        text: confirmed ? concatenatedText : { raw: "", html: "" },
      };

      if (confirmed) {
        console.log("[ImportDataManager] Imported data:", finalResult);
      }

      this.selectedItems = {};
      this.currentImporterId = "";
      this.currentImportParams = undefined;
      this.pluginTexts = {};

      return finalResult;
    } catch (error) {
      this.selectedItems = {};
      this.currentImporterId = "";
      this.currentImportParams = undefined;
      this.pluginTexts = {};
      throw error;
    }
  }

  selectItems(payload: { pluginId: string; data: any[]; text: { raw: string; html: string } }): void {
    this.selectedItems[payload.pluginId] = payload.data;
    this.pluginTexts[payload.pluginId] = payload.text;
  }

  getCurrentImporterId(): string {
    return this.currentImporterId;
  }

  getCurrentImportParams(): ImportParams | undefined {
    return this.currentImportParams;
  }

  private getConcatenatedText(): { raw: string; html: string } {
    const rawTexts: string[] = [];
    const htmlTexts: string[] = [];

    for (const text of Object.values(this.pluginTexts)) {
      if (text.raw) rawTexts.push(text.raw);
      if (text.html) htmlTexts.push(text.html);
    }

    return {
      raw: rawTexts.join("\n\n"),
      html: htmlTexts.join("<br><br>"),
    };
  }
}
