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

export interface DeleteResult {
  success: boolean;
  options: {
    deleteHalo: boolean;
    deleteLocal: boolean;
  };
}

export function openDeleteConfirmModal(
  plugin: HaloPlugin,
  site: HaloSite,
  title: string,
  postName: string,
): Promise<DeleteResult> {
  return new Promise((resolve) => {
    const modal = new DeleteConfirmModal(plugin, site, title, postName, (result) => {
      resolve(result);
    });
    modal.open();
  });
}

class DeleteConfirmModal extends Modal {
  private deleteHalo = true;
  private deleteLocal = false;

  constructor(
    private readonly plugin: HaloPlugin,
    private readonly site: HaloSite,
    private readonly title: string,
    private readonly postName: string,
    private readonly onResult: (result: DeleteResult) => void,
  ) {
    super(app);
  }

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

    contentEl.createEl("h2", {
      text: i18next.t("post_delete_modal.title"),
    });

    contentEl.createEl("p", {
      text: i18next.t("post_delete_modal.message", { title: this.title }),
      cls: "delete-message",
    });

    const optionsEl = contentEl.createDiv("delete-options");

    new Setting(optionsEl)
      .setName(i18next.t("post_delete_modal.message_halo_only").split("，")[0])
      .setDesc(i18next.t("post_delete_modal.message_halo_only").split("，").slice(1).join("，"))
      .addToggle((toggle) => {
        toggle.setValue(this.deleteHalo).onChange((value) => {
          this.deleteHalo = value;
        });
      });

    new Setting(optionsEl)
      .setName(i18next.t("post_delete_modal.message_local_only").split("，")[0])
      .setDesc(i18next.t("post_delete_modal.message_local_only").split("，").slice(1).join("，"))
      .addToggle((toggle) => {
        toggle.setValue(this.deleteLocal).onChange((value) => {
          this.deleteLocal = value;
        });
      });

    const foundFile = Array.from(this.plugin.app.vault.getFiles()).find((f: TFile) => f.basename === this.title);
    const abstractFile = this.plugin.app.vault.getAbstractFileByPath(`/${this.title}.md`);
    const localFile = (foundFile || (abstractFile instanceof TFile ? abstractFile : null));
    const hasLocalFile = localFile ? this.plugin.app.metadataCache.getFileCache(localFile) : null;

    if (!hasLocalFile) {
      const localFile = this.plugin.app.vault.getAbstractFileByPath(`/${this.title}.md`);
      if (!localFile) {
        const localToggle = optionsEl.querySelector('.setting-item:nth-child(2) input[type="checkbox"]') as HTMLInputElement;
        if (localToggle) {
          localToggle.disabled = true;
        }
      }
    }

    const actionsEl = contentEl.createDiv("delete-actions");

    new Setting(actionsEl)
      .addButton((button) => {
        button
          .setButtonText(i18next.t("post_delete_modal.button_delete_both"))
          .setWarning()
          .onClick(() => {
            if (!this.deleteHalo && !this.deleteLocal) {
              new Notice(i18next.t("post_delete_modal.error_no_option_selected"));
              return;
            }
            this.onResult({
              success: true,
              options: {
                deleteHalo: this.deleteHalo,
                deleteLocal: this.deleteLocal,
              },
            });
            this.close();
          });
      })
      .addButton((button) => {
        button
          .setButtonText(i18next.t("common.button_cancel"))
          .onClick(() => {
            this.onResult({
              success: false,
              options: {
                deleteHalo: false,
                deleteLocal: false,
              },
            });
            this.close();
          });
      });
  }

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