const DOCUMENT_STATUS_LABELS = {
  draft: '草稿',
  submitted: '审批中',
  pending: '待处理',
  approved: '已审批',
  completed: '已完成',
  archived: '已归档',
  returned: '已退回',
  rejected: '已驳回',
  pending_payment: '待付款',
  paid: '已付款'
}

function normalizeTableHeaderCell(value = '') {
  return String(value || '').replace(/\s+/g, '').trim()
}

function findTableColumnIndex(normalizedHeader = [], labels = []) {
  return labels
    .map((label) => normalizedHeader.indexOf(label))
    .find((index) => index >= 0) ?? -1
}

function resolveTableCell(row = [], normalizedHeader = [], labels = []) {
  const columnIndex = findTableColumnIndex(normalizedHeader, labels)
  return columnIndex >= 0 ? String(row[columnIndex] || '').trim() : ''
}

function hasMeaningfulTableValue(value = '') {
  const text = String(value || '').trim()
  return Boolean(text && text !== '-')
}

function normalizeDocumentStatusLabel(status = '') {
  const text = String(status || '').trim()
  if (!text || text === '-') {
    return ''
  }
  return DOCUMENT_STATUS_LABELS[text.toLowerCase()] || text
}

function resolveDocumentRecordTone(status = '', stage = '') {
  const normalizedStatus = normalizeDocumentStatusLabel(status)
  const text = `${normalizedStatus || String(status || '')} ${String(stage || '')}`.trim()
  if (/已删除|已驳回|驳回|拒绝|失败/.test(text)) {
    return 'is-danger'
  }
  if (/已审批|审批通过|已完成|已归档|已付款|已支付|可通过/.test(text)) {
    return 'is-success'
  }
  if (/草稿|待提交|待补充|已退回|退回/.test(text)) {
    return 'is-warning'
  }
  return 'is-pending'
}

function isDocumentRecordTable(normalizedHeader = []) {
  return (
    normalizedHeader.includes('单据编号') &&
    normalizedHeader.includes('操作') &&
    normalizedHeader.some((label) => ['单据类型', '申请时间', '单据状态', '状态', '当前节点', '事由'].includes(label))
  )
}

function renderDocumentCardField(label = '', value = '', options = {}, context = {}) {
  if (!hasMeaningfulTableValue(value)) {
    return ''
  }
  const renderInlineHtml = context.renderInlineHtml || ((item) => String(item || ''))
  const valueClass = options.valueClass ? ` ${options.valueClass}` : ''
  return [
    `<div class="ai-document-card__field${options.fieldClass ? ` ${options.fieldClass}` : ''}">`,
    `<span class="ai-document-card__label">${context.escapeHtml(label)}</span>`,
    `<strong class="ai-document-card__value${valueClass}">${renderInlineHtml(value)}</strong>`,
    '</div>'
  ].join('')
}

function renderDocumentCardAction(action = '', context = {}) {
  if (!hasMeaningfulTableValue(action)) {
    return ''
  }
  const renderInlineHtml = context.renderInlineHtml || ((item) => String(item || ''))
  const actionHtml = renderInlineHtml(action).replace(
    /class="ai-html-action-link\s+/g,
    'class="ai-html-action-link ai-document-card__action '
  )
  return [
    '<div class="ai-document-card__field ai-document-card__field--action">',
    '<span class="ai-document-card__label">操作</span>',
    actionHtml,
    '</div>'
  ].join('')
}

function renderDocumentRecordList(header = [], bodyRows = [], context = {}) {
  const normalizedHeader = header.map((cell) => normalizeTableHeaderCell(cell))
  const items = bodyRows.map((row) => {
    const documentType = resolveTableCell(row, normalizedHeader, ['单据类型'])
    const documentNo = resolveTableCell(row, normalizedHeader, ['单据编号'])
    const applyTime = resolveTableCell(row, normalizedHeader, ['申请时间', '日期', '时间'])
    const location = resolveTableCell(row, normalizedHeader, ['地点', '目的地'])
    const amount = resolveTableCell(row, normalizedHeader, ['金额', '预计金额', '报销金额'])
    const status = normalizeDocumentStatusLabel(resolveTableCell(row, normalizedHeader, ['单据状态', '状态']))
    const stage = resolveTableCell(row, normalizedHeader, ['当前节点'])
    const reason = resolveTableCell(row, normalizedHeader, ['事由'])
    const action = resolveTableCell(row, normalizedHeader, ['操作'])
    const tone = resolveDocumentRecordTone(status, stage)
    const title = documentType || reason || documentNo || '单据详情'
    const summarySecondField = amount
      ? renderDocumentCardField('金额', amount, { valueClass: 'ai-document-card__amount' }, context)
      : renderDocumentCardField('当前节点', stage || status || '待确认', {}, context)
    const summaryHtml = [
      renderDocumentCardField('日期', applyTime || '待补充', {}, context),
      summarySecondField
    ].join('')
    const detailsHtml = [
      renderDocumentCardField('地点', location || '待补充', {}, context),
      renderDocumentCardField('单据编号', documentNo, { valueClass: 'ai-document-card__number' }, context),
      renderDocumentCardField('事由', reason || '待补充', {}, context),
      amount ? renderDocumentCardField('当前节点', stage || status || '待确认', {}, context) : '',
      renderDocumentCardAction(action, context),
      renderDocumentCardField('单据类型', documentType, {}, context)
    ].join('')
    return [
      `<article class="ai-document-card ${tone}" role="listitem" aria-label="单据详情">`,
      '<header class="ai-document-card__head">',
      `<strong class="ai-document-card__reason">${context.renderInlineHtml(title)}</strong>`,
      hasMeaningfulTableValue(status) ? `<span class="ai-document-card__status">${context.renderInlineHtml(status)}</span>` : '',
      '</header>',
      '<div class="ai-document-card__body">',
      summaryHtml ? `<div class="ai-document-card__summary">${summaryHtml}</div>` : '',
      '<div class="ai-document-card__details">',
      detailsHtml,
      '</div>',
      '</div>',
      '</article>'
    ].join('')
  }).filter(Boolean)

  return [
    '<section class="ai-document-card-list" role="list" aria-label="单据结果">',
    ...items,
    '</section>'
  ].join('')
}

export function parseTableRow(line = '') {
  const trimmed = String(line || '').trim()
  if (!trimmed.startsWith('|')) {
    return []
  }
  return trimmed
    .replace(/^\|/, '')
    .replace(/\|$/, '')
    .split('|')
    .map((cell) => cell.trim())
}

export function renderTable(lines = [], options = {}) {
  const context = {
    escapeHtml: options.escapeHtml || ((item) => String(item || '')),
    renderInlineHtml: options.renderInlineHtml || ((item) => String(item || ''))
  }
  const rows = lines.map((line) => parseTableRow(line)).filter((row) => row.length)
  if (rows.length < 2) {
    return ''
  }
  const header = rows[0]
  const bodyRows = rows.slice(2)
  const normalizedHeader = header.map((cell) => normalizeTableHeaderCell(cell))
  if (isDocumentRecordTable(normalizedHeader)) {
    return renderDocumentRecordList(header, bodyRows, context)
  }

  return [
    '<div class="ai-html-table-wrap">',
    '<table>',
    '<thead><tr>',
    ...header.map((cell) => `<th>${context.renderInlineHtml(cell)}</th>`),
    '</tr></thead>',
    '<tbody>',
    ...bodyRows.map((row) => [
      '<tr>',
      ...header.map((_cell, index) => `<td>${context.renderInlineHtml(row[index] || '')}</td>`),
      '</tr>'
    ].join('')),
    '</tbody>',
    '</table>',
    '</div>'
  ].join('')
}
