import i18next from "i18next";
import { Modal, Notice } 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();
}

interface CategoryFormData {
  name: string;
  slug: string;
  priority: number;
}

class CategoryFormModal extends Modal {
  private category: { metadata: { name: string }; spec: { displayName: string; slug: string; priority: number } } | null = null;
  private isEdit = false;
  private onSubmit: (data: CategoryFormData) => void;

  constructor(
    private plugin: HaloPlugin,
    private site: HaloSite,
    category: CategoryFormModal["category"],
    private onSubmitFn: (data: CategoryFormData) => void
  ) {
    super(app);
    this.category = category;
    this.isEdit = !!category;
    this.onSubmit = onSubmitFn;
  }

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

    const modalEl = contentEl.createDiv("halo-modal");
    modalEl.style.cssText = `
      position: fixed; inset: 0; z-index: 1000;
      display: flex; align-items: center; justify-content: center;
      background: rgba(0,0,0,0.5); -webkit-backdrop-filter: blur(4px);
    `;

    const content = modalEl.createDiv("halo-card");
    content.style.cssText = `
      width: 100%; max-width: 440px; max-height: 90vh; overflow-y: auto;
      padding: var(--space-6);
    `;

    const header = content.createDiv("halo-modal-header");
    header.style.cssText = "margin-bottom: var(--space-4);";

    const title = header.createEl("h3");
    title.textContent = this.isEdit
      ? i18next.t("category_manager_modal.title_edit")
      : i18next.t("category_manager_modal.title_create");
    title.style.cssText = "font-size: 18px; font-weight: 600; margin: 0;";

    const closeBtn = header.createEl("button", { text: "✕" });
    closeBtn.className = "halo-modal-close";
    closeBtn.style.cssText = `
      display: flex; align-items: center; justify-content: center;
      width: 32px; height: 32px; background: transparent; border: none;
      border-radius: 8px; color: var(--text-muted); cursor: pointer; font-size: 16px;
    `;
    closeBtn.addEventListener("click", () => this.close());

    const form = content.createDiv("halo-modal-body");

    // Name field
    const nameGroup = form.createDiv("halo-form-group");
    const nameLabel = nameGroup.createEl("label", { text: i18next.t("category_manager_modal.column_name") });
    nameLabel.className = "halo-form-label";
    const nameInput = nameGroup.createEl("input", { type: "text" }) as HTMLInputElement;
    nameInput.className = "halo-input";
    nameInput.style.cssText = "width: 100%;";
    nameInput.value = this.category?.spec.displayName || "";
    nameInput.placeholder = i18next.t("category_manager_modal.prompt_name");

    // Slug field
    const slugGroup = form.createDiv("halo-form-group");
    const slugLabel = slugGroup.createEl("label", { text: i18next.t("category_manager_modal.column_slug") });
    slugLabel.className = "halo-form-label";
    const slugInput = slugGroup.createEl("input", { type: "text" }) as HTMLInputElement;
    slugInput.className = "halo-input";
    slugInput.style.cssText = "width: 100%;";
    slugInput.value = this.category?.spec.slug || "";
    slugInput.placeholder = i18next.t("category_manager_modal.prompt_slug");

    // Priority field
    const priorityGroup = form.createDiv("halo-form-group");
    const priorityLabel = priorityGroup.createEl("label", { text: i18next.t("category_manager_modal.column_priority") });
    priorityLabel.className = "halo-form-label";
    const priorityInput = priorityGroup.createEl("input", { type: "number" }) as HTMLInputElement;
    priorityInput.className = "halo-input";
    priorityInput.style.cssText = "width: 100%;";
    priorityInput.value = String(this.category?.spec.priority ?? 0);
    priorityInput.placeholder = i18next.t("category_manager_modal.prompt_priority");

    // Footer buttons
    const footer = content.createDiv("halo-modal-footer");
    footer.style.cssText = "margin-top: var(--space-4);";

    const cancelBtn = footer.createEl("button", { text: i18next.t("common.button_cancel") });
    cancelBtn.className = "halo-btn halo-btn-secondary";
    cancelBtn.addEventListener("click", () => this.close());

    const submitBtn = footer.createEl("button", { text: this.isEdit ? i18next.t("common.button_save") : i18next.t("category_manager_modal.button_create") });
    submitBtn.className = "halo-btn halo-btn-primary";

    submitBtn.addEventListener("click", () => {
      const name = nameInput.value.trim();
      const slug = slugInput.value.trim() || this.generateSlug(name);
      const priority = parseInt(priorityInput.value) || 0;

      if (!name) {
        nameInput.classList.add("error");
        return;
      }

      this.onSubmit({ name, slug, priority });
      this.close();
    });

    // Auto-generate slug on name change
    nameInput.addEventListener("input", () => {
      if (!this.isEdit || !this.category) {
        slugInput.value = this.generateSlug(nameInput.value);
      }
    });

    modalEl.addEventListener("click", (e) => {
      if (e.target === modalEl) this.close();
    });

    nameInput.focus();
  }

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

class CategoryManagerModal extends Modal {
  private categories: Array<{ metadata: { name: string }; spec: { displayName: string; slug: string; priority: number } }> = [];
  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"),
      cls: "modal-title"
    });

    const actionsEl = contentEl.createDiv("category-manager-actions");
    actionsEl.style.cssText = "display: flex; justify-content: space-between; align-items: center; padding: var(--space-4);";

    const createBtn = actionsEl.createEl("button", {
      text: i18next.t("category_manager_modal.button_create"),
      cls: "halo-btn halo-btn-primary"
    });
    createBtn.addEventListener("click", () => this.showCreateCategoryForm());

    const closeBtn = actionsEl.createEl("button", {
      text: i18next.t("common.button_close"),
      cls: "halo-btn halo-btn-secondary"
    });
    closeBtn.addEventListener("click", () => this.close());

    const listEl = contentEl.createDiv("category-list");
    listEl.style.cssText = "padding: 0 var(--space-4) var(--space-4);";

    const loadingEl = listEl.createDiv("halo-empty");
    loadingEl.style.cssText = "padding: var(--space-6);";
    loadingEl.innerHTML = `<div class="halo-spinner"></div><p style="margin-top: var(--space-3); color: var(--text-muted);">${i18next.t("category_manager_modal.loading")}</p>`;

    try {
      const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
      this.categories = await service.getCategories();
      this.loading = false;
      this.renderCategoryList();
    } catch {
      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) {
      const emptyEl = listEl.createDiv("halo-empty");
      emptyEl.innerHTML = `
        <div style="font-size: 48px; opacity: 0.5;">📁</div>
        <p style="margin-top: var(--space-3); font-weight: 500;">${i18next.t("category_manager_modal.empty")}</p>
      `;
      return;
    }

    const table = listEl.createEl("table", { cls: "halo-table" });
    const header = table.createEl("thead").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"), cls: "text-right" });

    const tbody = table.createEl("tbody");

    for (const category of this.categories) {
      const row = tbody.createEl("tr");

      const nameCell = row.createEl("td");
      nameCell.style.cssText = "font-weight: 500;";
      nameCell.textContent = category.spec.displayName;

      row.createEl("td", { text: category.spec.slug });

      const priorityCell = row.createEl("td");
      const priorityBadge = priorityCell.createEl("span", { text: String(category.spec.priority || 0) });
      priorityBadge.style.cssText = `
        display: inline-flex; align-items: center; justify-content: center;
        min-width: 28px; height: 22px; padding: 0 8px;
        background: var(--background-secondary); border-radius: var(--radius-full);
        font-size: var(--font-size-xs); font-weight: 500;
      `;

      const actionsCell = row.createEl("td");
      actionsCell.style.cssText = "text-align: right;";

      const editBtn = actionsCell.createEl("button", {
        text: i18next.t("category_manager_modal.button_edit"),
        cls: "halo-btn halo-btn-sm halo-btn-ghost"
      });
      editBtn.addEventListener("click", () => this.showEditCategoryForm(category));

      const deleteBtn = actionsCell.createEl("button", {
        text: i18next.t("category_manager_modal.button_delete"),
        cls: "halo-btn halo-btn-sm halo-btn-ghost"
      });
      deleteBtn.style.cssText += "color: var(--halo-danger);";
      deleteBtn.addEventListener("click", () => this.showDeleteCategoryDialog(category));
    }
  }

  private showCreateCategoryForm() {
    new CategoryFormModal(this.plugin, this.site, null, async (data) => {
      try {
        const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
        await service.createCategory(data.name, data.slug, data.priority);
        new Notice(i18next.t("category_manager_modal.notice_create_success"));
        this.categories = await service.getCategories();
        this.renderCategoryList();
      } catch {
        new Notice(i18next.t("category_manager_modal.error_create_failed"));
      }
    });
  }

  private showEditCategoryForm(category: typeof this.categories[0]) {
    new CategoryFormModal(this.plugin, this.site, category, async (data) => {
      try {
        const service = new HaloService(this.plugin.app, this.plugin.settings, this.site);
        await service.updateCategory(category.metadata.name, data.name, data.slug, data.priority);
        new Notice(i18next.t("category_manager_modal.notice_update_success"));
        this.categories = await service.getCategories();
        this.renderCategoryList();
      } catch {
        new Notice(i18next.t("category_manager_modal.error_update_failed"));
      }
    });
  }

  private showDeleteCategoryDialog(category: typeof this.categories[0]) {
    const modalEl = document.createElement("div");
    modalEl.style.cssText = `
      position: fixed; inset: 0; z-index: 1000;
      display: flex; align-items: center; justify-content: center;
      background: rgba(0,0,0,0.5); -webkit-backdrop-filter: blur(4px);
    `;

    const content = modalEl.createDiv("halo-card");
    content.style.cssText = "width: 100%; max-width: 400px; padding: var(--space-6);";

    const title = content.createEl("h3", {
      text: i18next.t("category_manager_modal.confirm_delete", { name: category.spec.displayName })
    });
    title.style.cssText = "font-size: 16px; font-weight: 600; margin: 0 0 var(--space-4) 0;";

    const actions = content.createDiv("halo-modal-footer");
    actions.style.cssText = "margin-top: var(--space-4);";

    const cancelBtn = actions.createEl("button", {
      text: i18next.t("common.button_cancel"),
      cls: "halo-btn halo-btn-secondary"
    });
    cancelBtn.addEventListener("click", () => modalEl.remove());

    const deleteBtn = actions.createEl("button", {
      text: i18next.t("common.button_delete"),
      cls: "halo-btn halo-btn-danger"
    });
    deleteBtn.addEventListener("click", async () => {
      modalEl.remove();
      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 {
        new Notice(i18next.t("category_manager_modal.error_delete_failed"));
      }
    });

    modalEl.addEventListener("click", (e) => {
      if (e.target === modalEl) modalEl.remove();
    });

    document.body.appendChild(modalEl);
  }

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