import { getStatusLabel, getStatusTone, normalizeStatusValue } from "./statusToneMap";

const STATUS_TONE_CLASS_PREFIX = "status-tone-";

function isStatusLikeHeader(label) {
  if (!label) {
    return false;
  }

  return (
    label.includes("状态") ||
    label.includes("同步") ||
    label.includes("审核") ||
    label.includes("检验结果") ||
    label.includes("质检结果") ||
    label.includes("处置方式") ||
    label === "方式"
  );
}

function clearAutoStatusElement(element) {
  const previousAutoTone = element.dataset.autoStatusTone;
  if (previousAutoTone) {
    element.classList.remove(`${STATUS_TONE_CLASS_PREFIX}${previousAutoTone}`);
    delete element.dataset.autoStatusTone;
  }
  element.classList.remove("status-badge-auto", "status-value-cell");
}

function markStatusElement(element, value) {
  const tone = getStatusTone(value);
  const toneClass = tone ? `${STATUS_TONE_CLASS_PREFIX}${tone}` : "";
  clearAutoStatusElement(element);
  element.classList.toggle("status-badge-auto", Boolean(tone));
  element.classList.toggle("status-value-cell", element.tagName === "TD" && Boolean(tone));
  if (tone) {
    element.classList.add(toneClass);
    element.dataset.autoStatusTone = tone;
    const label = getStatusLabel(value);
    if (element.textContent !== label) {
      element.textContent = label;
    }
  }
}

function hasRecognizedStatus(value) {
  const rawValue = normalizeStatusValue(value);
  if (!rawValue || rawValue === "-") {
    return false;
  }
  const label = getStatusLabel(value);
  return getStatusTone(value) !== "info" || normalizeStatusValue(label) !== rawValue;
}

function wrapPlainStatusCell(cell) {
  if (cell.dataset.statusWrapped === "1") {
    if (cell.firstElementChild) {
      return cell.firstElementChild;
    }
    delete cell.dataset.statusWrapped;
  }

  if (cell.children.length > 0) {
    return cell.children.length === 1 ? cell.firstElementChild : cell;
  }

  const value = cell.textContent.trim();
  if (!getStatusTone(value)) {
    return cell;
  }

  const badge = document.createElement("span");
  badge.textContent = getStatusLabel(value);
  cell.textContent = "";
  cell.appendChild(badge);
  cell.dataset.statusWrapped = "1";
  return badge;
}

function enhanceTableStatuses(root) {
  root.querySelectorAll("table").forEach((table) => {
    const headers = Array.from(table.querySelectorAll("thead th"));
    const statusColumnIndexes = headers
      .map((header, index) => ({ index, label: normalizeStatusValue(header.textContent) }))
      .filter((item) => isStatusLikeHeader(item.label))
      .map((item) => item.index);

    if (!statusColumnIndexes.length) {
      return;
    }

    table.querySelectorAll("tbody tr").forEach((row) => {
      const cells = Array.from(row.children).filter((cell) => cell.tagName === "TD");
      statusColumnIndexes.forEach((index) => {
        const cell = cells[index];
        if (!cell || cell.querySelector("button, a, input, select, textarea")) {
          return;
        }
        const target = wrapPlainStatusCell(cell);
        markStatusElement(target, target.textContent);
      });
    });
  });
}

function enhanceDetailStatuses(root) {
  root.querySelectorAll(".detail-item, .detail-block").forEach((item) => {
    const label = normalizeStatusValue(item.querySelector("span")?.textContent || "");
    if (!label.includes("状态")) {
      return;
    }
    const valueElement = item.querySelector("strong") || item;
    markStatusElement(valueElement, valueElement.textContent);
  });

  root.querySelectorAll("dl").forEach((list) => {
    const terms = Array.from(list.querySelectorAll("dt"));
    terms.forEach((term) => {
      if (!normalizeStatusValue(term.textContent).includes("状态")) {
        return;
      }
      const valueElement = term.nextElementSibling;
      if (valueElement) {
        markStatusElement(valueElement, valueElement.textContent);
      }
    });
  });

  root.querySelectorAll(".table-chip, .table-badge, .status-chip").forEach((element) => {
    if (hasRecognizedStatus(element.textContent)) {
      markStatusElement(element, element.textContent);
    } else {
      clearAutoStatusElement(element);
    }
  });
}

export function enhanceStatusBadges(root = document) {
  enhanceTableStatuses(root);
  enhanceDetailStatuses(root);
}

export function setupStatusBadgeEnhancer() {
  let frame = 0;

  const scheduleEnhance = () => {
    if (frame) {
      return;
    }
    frame = window.requestAnimationFrame(() => {
      frame = 0;
      enhanceStatusBadges(document);
    });
  };

  const observer = new MutationObserver(scheduleEnhance);
  observer.observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true
  });
  scheduleEnhance();

  return () => {
    if (frame) {
      window.cancelAnimationFrame(frame);
    }
    observer.disconnect();
  };
}
