import { api } from "../../../services/api";
import type { DictionaryItem, DictionaryResponse } from "../../../types";
import { confirmDialog, formDialog, notify, notifyError } from "../../../ui/dialogs";
import { escapeHtml } from "../../../utils/format";
import { appState } from "../appState";

type DictionaryKind = "brands" | "types";

type DictionaryManageResult = {
  changed: boolean;
};

const dictionaryLabels: Record<DictionaryKind, string> = {
  brands: "品牌",
  types: "类型"
};

let changed = false;

export async function openDictionaryManager(onChanged?: () => Promise<void> | void) {
  changed = false;
  await refreshDictionaries();
  const result = await formDialog<DictionaryManageResult>({
    title: "品牌 / 类型维护",
    width: 680,
    height: 520,
    blockPage: false,
    body: `
      <div class="dictionary-manager">
        ${dictionaryPanelHtml("brands", "品牌")}
        ${dictionaryPanelHtml("types", "类型")}
      </div>
    `,
    onOpen: bindDictionaryEvents,
    onSubmit: () => ({ changed })
  });

  if (result?.changed) {
    await onChanged?.();
  }
}

async function refreshDictionaries() {
  const result = await api<DictionaryResponse>("/api/dictionaries");
  appState.brands = result.brands;
  appState.types = result.types;
}

function dictionaryPanelHtml(kind: DictionaryKind, title: string) {
  const items = kind === "brands" ? appState.brands : appState.types;
  return `
    <section class="dictionary-panel" data-kind="${kind}">
      <header class="dictionary-panel-head">
        <div class="dictionary-title">
          <i aria-hidden="true"></i>
          <strong>${title}</strong>
        </div>
        <span class="dictionary-count">${items.length} 项</span>
      </header>
      <div class="dictionary-editor">
        <input data-role="name-input" data-kind="${kind}" placeholder="${title}名称" />
        <button class="primary-btn dictionary-save-btn" type="button" data-action="save" data-kind="${kind}">新增</button>
        <button class="ghost-btn dictionary-cancel-btn" type="button" data-action="cancel" data-kind="${kind}" hidden>取消</button>
      </div>
      <div class="dictionary-list-head">
        <span>名称</span>
        <span>操作</span>
      </div>
      <div class="dictionary-list">
        ${items.map((item) => dictionaryItemHtml(kind, item)).join("") || `<div class="dictionary-empty">暂无数据</div>`}
      </div>
    </section>
  `;
}

function dictionaryItemHtml(kind: DictionaryKind, item: DictionaryItem) {
  return `
    <div class="dictionary-item" data-kind="${kind}" data-id="${item.id}" data-name="${escapeHtml(item.name)}">
      <span class="dictionary-name" title="${escapeHtml(item.name)}">${escapeHtml(item.name)}</span>
      <div class="dictionary-row-actions">
        <button class="dictionary-edit-btn" type="button" data-action="edit" data-kind="${kind}" data-id="${item.id}">编辑</button>
        <button class="danger-text-btn dictionary-delete-btn" type="button" data-action="delete" data-kind="${kind}" data-id="${item.id}">删除</button>
      </div>
    </div>
  `;
}

function bindDictionaryEvents() {
  document.querySelectorAll<HTMLButtonElement>(".dictionary-manager button").forEach((button) => {
    button.addEventListener("click", async () => {
      try {
        const kind = button.dataset.kind as DictionaryKind;
        const action = button.dataset.action;
        const id = Number(button.dataset.id);
        if (action === "save") await saveDictionaryItem(kind);
        if (action === "cancel") resetDictionaryEditor(kind);
        if (action === "edit") editDictionaryItem(kind, id);
        if (action === "delete") await deleteDictionaryItem(kind, id);
      } catch (error) {
        notifyError(error);
      }
    });
  });
}

async function saveDictionaryItem(kind: DictionaryKind) {
  const input = getDictionaryInput(kind);
  const name = input?.value.trim() ?? "";
  if (!name) {
    notify(`${dictionaryLabels[kind]}名称不能为空`);
    return;
  }
  const editingId = input?.dataset.editingId;
  await api(editingId ? `/api/dictionaries/${kind}/${editingId}` : `/api/dictionaries/${kind}`, {
    method: editingId ? "PUT" : "POST",
    body: JSON.stringify({ name })
  });
  changed = true;
  notify(editingId ? "保存成功" : "新增成功");
  await rerenderDictionaryManager();
}

function editDictionaryItem(kind: DictionaryKind, id: number) {
  const current = findDictionaryItem(kind, id);
  const input = getDictionaryInput(kind);
  if (!current || !input) return;
  input.value = current.name;
  input.dataset.editingId = String(id);
  const panel = document.querySelector<HTMLElement>(`.dictionary-panel[data-kind="${kind}"]`);
  const saveButton = panel?.querySelector<HTMLButtonElement>('button[data-action="save"]');
  const cancelButton = panel?.querySelector<HTMLButtonElement>('button[data-action="cancel"]');
  if (saveButton) saveButton.textContent = "保存";
  if (cancelButton) cancelButton.hidden = false;
  input.focus();
}

function resetDictionaryEditor(kind: DictionaryKind) {
  const input = getDictionaryInput(kind);
  const panel = document.querySelector<HTMLElement>(`.dictionary-panel[data-kind="${kind}"]`);
  const saveButton = panel?.querySelector<HTMLButtonElement>('button[data-action="save"]');
  const cancelButton = panel?.querySelector<HTMLButtonElement>('button[data-action="cancel"]');
  if (input) {
    input.value = "";
    delete input.dataset.editingId;
  }
  if (saveButton) saveButton.textContent = "新增";
  if (cancelButton) cancelButton.hidden = true;
}

function getDictionaryInput(kind: DictionaryKind) {
  return document.querySelector<HTMLInputElement>(`.dictionary-panel[data-kind="${kind}"] input[data-role="name-input"]`);
}

async function deleteDictionaryItem(kind: DictionaryKind, id: number) {
  const current = findDictionaryItem(kind, id);
  if (!current) return;
  const confirmed = await confirmDialog(`删除 ${dictionaryLabels[kind]}「${current.name}」后，已引用该项的模型会清空该字段，是否继续？`);
  if (!confirmed) return;
  await api(`/api/dictionaries/${kind}/${id}`, { method: "DELETE" });
  changed = true;
  notify("删除成功");
  await rerenderDictionaryManager();
}

function findDictionaryItem(kind: DictionaryKind, id: number) {
  const items = kind === "brands" ? appState.brands : appState.types;
  return items.find((item) => item.id === id);
}

async function rerenderDictionaryManager() {
  await refreshDictionaries();
  const container = document.querySelector<HTMLDivElement>(".dictionary-manager");
  if (!container) return;
  container.innerHTML = `${dictionaryPanelHtml("brands", "品牌")}${dictionaryPanelHtml("types", "类型")}`;
  bindDictionaryEvents();
}
