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 openCategoryManagerModal(plugin: HaloPlugin, site: HaloSite): void {
  const modal = new CategoryManagerModal(plugin, site);
  modal.open();
}

class CategoryManagerModal extends Modal {
  private categories: 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("category_manager_modal.title"),
    });

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

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

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

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

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

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

    for (const category of this.categories) {
      const row = table.createEl("tr");
      
      row.createEl("td", { text: category.spec.displayName });
      row.createEl("td", { text: category.spec.slug });
      row.createEl("td", { text: String(category.spec.priority || 0) });
      
      const actionsCell = row.createEl("td");
      actionsCell.createEl("button", {
        text: i18next.t("category_manager_modal.button_edit"),
        cls: "category-action-btn",
      }).addEventListener("click", () => {
        this.showEditCategoryDialog(category);
      });
      
      actionsCell.createEl("button", {
        text: i18next.t("category_manager_modal.button_delete"),
        cls: "category-action-btn danger",
      }).addEventListener("click", () => {
        this.showDeleteCategoryDialog(category);
      });
    }
  }

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

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

    const priority = prompt(i18next.t("category_manager_modal.prompt_priority"), "0");
    if (priority === null) return;

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.createCategory(name, slug, parseInt(priority) || 0);
      new Notice(i18next.t("category_manager_modal.notice_create_success"));
      
      this.categories = await service.getCategories();
      this.renderCategoryList();
    } catch (error) {
      new Notice(i18next.t("category_manager_modal.error_create_failed"));
    }
  }

  private async showEditCategoryDialog(category: any) {
    const name = prompt(i18next.t("category_manager_modal.prompt_name"), category.spec.displayName);
    if (name === null) return;

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

    const priority = prompt(i18next.t("category_manager_modal.prompt_priority"), String(category.spec.priority || 0));
    if (priority === null) return;

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.updateCategory(category.metadata.name, name, slug, parseInt(priority) || 0);
      new Notice(i18next.t("category_manager_modal.notice_update_success"));
      
      this.categories = await service.getCategories();
      this.renderCategoryList();
    } catch (error) {
      new Notice(i18next.t("category_manager_modal.error_update_failed"));
    }
  }

  private async showDeleteCategoryDialog(category: any) {
    if (!confirm(i18next.t("category_manager_modal.confirm_delete", { name: category.spec.displayName }))) {
      return;
    }

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      await service.deleteCategory(category.metadata.name);
      new Notice(i18next.t("category_manager_modal.notice_delete_success"));
      
      this.categories = await service.getCategories();
      this.renderCategoryList();
    } catch (error) {
      new Notice(i18next.t("category_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();
  }
}