import i18next from "i18next";
import { Notice, TFile } from "obsidian";
import { openSiteSelectionModal } from "../site-selection-modal";
import { openFilePreviewModal, type ImportOptions } from "../modals/file-preview-modal";
import HaloService from "../service";
import type HaloPlugin from "../main";
import type { HaloSite } from "../settings";

export async function importFromMarkdownFile(plugin: HaloPlugin): Promise<void> {
  try {
    if (plugin.settings.sites.length === 0) {
      new Notice(i18next.t("command.pull_post.error_no_sites"));
      return;
    }

    let site: HaloSite = plugin.settings.sites[0];
    if (plugin.settings.sites.length > 1) {
      site = await openSiteSelectionModal(plugin);
    }

    const options: ImportOptions = {
      publishImmediately: plugin.settings.publishByDefault,
    };

    const file = await new Promise<TFile | null>((resolve) => {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".md";
      
      input.onchange = async () => {
        const selectedFile = input.files?.[0];
        if (!selectedFile) {
          resolve(null);
          return;
        }

        const allFiles = plugin.app.vault.getFiles();
        const matchedFile = allFiles.find(f => f.name === selectedFile.name);
        
        if (matchedFile) {
          resolve(matchedFile);
        } else {
          new Notice(i18next.t("import_modal.error_file_not_in_vault"));
          resolve(null);
        }
      };

      input.oncancel = () => resolve(null);
      input.click();
    });

    if (!file) {
      return;
    }

    const result = await openFilePreviewModal(plugin, site, file, options);

    if (!result.success) {
      return;
    }

    const service = new HaloService(plugin.app, plugin.settings, site);
    
    const success = await service.importPost(file, result.options.publishImmediately);

    if (success) {
      new Notice(i18next.t("service.notice_import_success"));
    } else {
      new Notice(i18next.t("service.error_import_failed"));
    }

  } catch (error) {
    console.error("[HaloPlugin] Import from markdown file failed:", error);
    new Notice(i18next.t("service.error_import_failed"));
  }
}