import i18next from "i18next";
import { Modal, Notice, Setting } from "obsidian";
import type { TFile } from "obsidian";
import type HaloPlugin from "../main";
import type { HaloSite } from "../settings";

export interface ImportOptions {
  publishImmediately: boolean;
}

export interface ImportResult {
  file: TFile;
  success: boolean;
}

export function openFilePreviewModal(
  plugin: HaloPlugin,
  site: HaloSite,
  file: TFile,
  options: ImportOptions,
): Promise<ImportResult> {
  return new Promise((resolve) => {
    const modal = new FilePreviewModal(plugin, site, file, options, (result) => {
      resolve(result);
    });
    modal.open();
  });
}

class FilePreviewModal extends Modal {
  constructor(
    private readonly plugin: HaloPlugin,
    private readonly site: HaloSite,
    private readonly file: TFile,
    private readonly options: ImportOptions,
    private readonly onResult: (result: ImportResult) => void,
  ) {
    super(app);
  }

  async onOpen() {
    const { contentEl } = this;
    contentEl.empty();

    const headerEl = contentEl.createDiv("file-preview-header");
    headerEl.createEl("h2", {
      text: i18next.t("file_preview_modal.title"),
    });
    headerEl.createEl("p", {
      text: this.file.path,
      cls: "file-path",
    });

    try {
      const content = await this.app.vault.read(this.file);
      const matterData = this.app.metadataCache.getFileCache(this.file)?.frontmatter;
      const frontmatterPosition = this.app.metadataCache.getFileCache(this.file)?.frontmatterPosition;

      const previewContent = contentEl.createDiv("file-preview-content");
      
      if (matterData) {
        const frontmatterEl = previewContent.createDiv("frontmatter-section");
        frontmatterEl.createEl("h3", {
          text: i18next.t("file_preview_modal.frontmatter"),
        });
        
        const frontmatterList = frontmatterEl.createEl("ul");
        if (matterData.title) {
          frontmatterList.createEl("li", { text: `Title: ${matterData.title}` });
        }
        if (matterData.slug) {
          frontmatterList.createEl("li", { text: `Slug: ${matterData.slug}` });
        }
        if (matterData.tags) {
          frontmatterList.createEl("li", { text: `Tags: ${Array.isArray(matterData.tags) ? matterData.tags.join(", ") : matterData.tags}` });
        }
        if (matterData.categories) {
          frontmatterList.createEl("li", { text: `Categories: ${Array.isArray(matterData.categories) ? matterData.categories.join(", ") : matterData.categories}` });
        }
      }

      const contentPreview = previewContent.createDiv("content-preview");
      contentPreview.createEl("h3", {
        text: i18next.t("file_preview_modal.content_preview"),
      });
      
      const contentText = frontmatterPosition 
        ? content.slice(frontmatterPosition.end.offset, Math.min(content.length, 500))
        : content.slice(0, 500);
      
      contentPreview.createEl("pre", {
        text: contentText + (content.length > 500 ? "..." : ""),
        cls: "content-text",
      });

      const actionsEl = contentEl.createDiv("file-preview-actions");
      
      const publishToggle = new Setting(actionsEl)
        .setName(i18next.t("file_preview_modal.publish_immediately"))
        .setDesc(i18next.t("file_preview_modal.publish_immediately_desc"))
        .addToggle((toggle) => {
          toggle.setValue(this.options.publishImmediately).onChange((value) => {
            this.options.publishImmediately = value;
          });
        });

      new Setting(actionsEl)
        .addButton((button) => {
          button
            .setButtonText(i18next.t("file_preview_modal.button_import"))
            .setCta()
            .onClick(() => {
              this.onResult({ file: this.file, success: true });
              this.close();
            });
        })
        .addButton((button) => {
          button
            .setButtonText(i18next.t("common.button_cancel"))
            .onClick(() => {
              this.onResult({ file: this.file, success: false });
              this.close();
            });
        });

    } catch (error) {
      new Notice(i18next.t("common.error_connection_failed"));
      this.close();
    }
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}