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

export function openTagManagerModal(plugin: HaloPlugin, site: HaloSite): void {
  const modal = new TagManagerModal(plugin, site);
  modal.open();
}

class TagManagerModal extends Modal {
  private tags: any[] = [];
  private loading = true;

  constructor(
    private readonly plugin: HaloPlugin,
    private readonly site: HaloSite,
  ) {
    super(app);
  }

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

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

    const actionsEl = contentEl.createDiv("tag-manager-actions");
    
    new Setting(actionsEl)
      .addButton((button) => {
        button
          .setButtonText(i18next.t("tag_manager_modal.button_create"))
          .setCta()
          .onClick(() => {
            this.showCreateTagDialog();
          });
      })
      .addButton((button) => {
        button
          .setButtonText(i18next.t("common.button_close"))
          .onClick(() => this.close());
      });

    const listEl = contentEl.createDiv("tag-list");
    listEl.createEl("p", { text: i18next.t("tag_manager_modal.loading") });

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      this.tags = await service.getTags();
      this.loading = false;
      this.renderTagList();
    } catch (error) {
      new Notice(i18next.t("common.error_connection_failed"));
      this.close();
    }
  }

  private renderTagList() {
    const { contentEl } = this;
    const listEl = contentEl.querySelector(".tag-list") as HTMLElement;
    
    if (!listEl) return;
    
    listEl.empty();

    if (this.tags.length === 0) {
      listEl.createEl("p", { text: i18next.t("tag_manager_modal.empty") });
      return;
    }

    const table = listEl.createEl("table", { cls: "tag-table" });
    const header = table.createEl("tr");
    header.createEl("th", { text: i18next.t("tag_manager_modal.column_name") });
    header.createEl("th", { text: i18next.t("tag_manager_modal.column_slug") });
    header.createEl("th", { text: i18next.t("tag_manager_modal.column_color") });
    header.createEl("th", { text: i18next.t("tag_manager_modal.column_actions") });

    for (const tag of this.tags) {
      const row = table.createEl("tr");
      
      row.createEl("td", { text: tag.spec.displayName });
      row.createEl("td", { text: tag.spec.slug });
      
      const colorCell = row.createEl("td");
      colorCell.createEl("span", {
        text: tag.spec.color || "#ffffff",
        cls: "tag-color-preview",
        attr: { style: `background-color: ${tag.spec.color || "#ffffff"}` }
      });
      
      const actionsCell = row.createEl("td");
      actionsCell.createEl("button", {
        text: i18next.t("tag_manager_modal.button_edit"),
        cls: "tag-action-btn",
      }).addEventListener("click", () => {
        this.showEditTagDialog(tag);
      });
      
      actionsCell.createEl("button", {
        text: i18next.t("tag_manager_modal.button_delete"),
        cls: "tag-action-btn danger",
      }).addEventListener("click", () => {
        this.showDeleteTagDialog(tag);
      });
    }
  }

  private async showCreateTagDialog() {
    const name = prompt(i18next.t("tag_manager_modal.prompt_name"));
    if (!name) return;

    const slug = prompt(i18next.t("tag_manager_modal.prompt_slug"), this.generateSlug(name));
    if (!slug) return;

    const color = prompt(i18next.t("tag_manager_modal.prompt_color"), "#4A90E2");
    if (!color) return;

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.createTag(name, slug, color);
      new Notice(i18next.t("tag_manager_modal.notice_create_success"));
      
      this.tags = await service.getTags();
      this.renderTagList();
    } catch (error) {
      new Notice(i18next.t("tag_manager_modal.error_create_failed"));
    }
  }

  private async showEditTagDialog(tag: any) {
    const name = prompt(i18next.t("tag_manager_modal.prompt_name"), tag.spec.displayName);
    if (name === null) return;

    const slug = prompt(i18next.t("tag_manager_modal.prompt_slug"), tag.spec.slug);
    if (slug === null) return;

    const color = prompt(i18next.t("tag_manager_modal.prompt_color"), tag.spec.color || "#4A90E2");
    if (color === null) return;

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.updateTag(tag.metadata.name, name, slug, color);
      new Notice(i18next.t("tag_manager_modal.notice_update_success"));
      
      this.tags = await service.getTags();
      this.renderTagList();
    } catch (error) {
      new Notice(i18next.t("tag_manager_modal.error_update_failed"));
    }
  }

  private async showDeleteTagDialog(tag: any) {
    if (!confirm(i18next.t("tag_manager_modal.confirm_delete", { name: tag.spec.displayName }))) {
      return;
    }

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.deleteTag(tag.metadata.name);
      new Notice(i18next.t("tag_manager_modal.notice_delete_success"));
      
      this.tags = await service.getTags();
      this.renderTagList();
    } catch (error) {
      new Notice(i18next.t("tag_manager_modal.error_delete_failed"));
    }
  }

  private generateSlug(name: string): string {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, "-")
      .replace(/^-|-$/g, "");
  }

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