/**
 * Planilha XLSX de uma aba a partir da tabela tipada da exportação (ADR 0069). Texto vai como
 * texto, número com o formato da coluna e data como data do Excel; o cabeçalho fica congelado.
 * Só para o servidor: a compactação usa o `zlib` do Node.
 */

import { deflateRawSync } from 'node:zlib'
import type { ListExportCell, ListExportColumn, ListExportTable } from '../core/index.ts'
import { XLSX_CONTENT_TYPE } from '../core/list-export.ts'

export { XLSX_CONTENT_TYPE }

// =============================================================================
// Formatos
// =============================================================================

const DATE_FORMAT = 'dd/mm/yyyy'
const DATE_TIME_FORMAT = 'dd/mm/yyyy hh:mm'

/** O código de formato do Excel equivalente ao `numberFormat` da coluna; `null` = Geral. */
export function excelNumberFormat(format: Intl.NumberFormatOptions | undefined): string | null {
  if (format === undefined) return null
  const decimals = format.maximumFractionDigits ?? format.minimumFractionDigits
  const fraction = (digits: number): string => (digits > 0 ? `.${'0'.repeat(Math.min(digits, 10))}` : '')
  if (format.style === 'currency') {
    const digits = decimals ?? 2
    const symbol = format.currency === undefined || format.currency === 'BRL' ? 'R$' : format.currency
    return `"${symbol}" #,##0${fraction(digits)}`
  }
  if (format.style === 'percent') return `0${fraction(decimals ?? 0)}%`
  // Sem casas declaradas, o Geral mostra o número como ele é, sem vírgula sobrando nos inteiros.
  if (decimals === undefined) return null
  return `${format.useGrouping === false ? '0' : '#,##0'}${fraction(decimals)}`
}

/** Dias desde 30/12/1899, o calendário do Excel, a partir do relógio local já resolvido. */
function excelSerial(wallClock: string): number {
  const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/.exec(wallClock)
  if (match === null) return Number.NaN
  const [, y, mo, d, h, mi, s] = match.map(Number) as [number, number, number, number, number, number, number]
  return Date.UTC(y, mo - 1, d, h, mi, s) / 86_400_000 + 25_569
}

// =============================================================================
// XML
// =============================================================================

// Caracteres que o XML 1.0 não aceita nem escapados; saem do texto em vez de corromper o arquivo.
// eslint-disable-next-line no-control-regex
const INVALID_XML = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g

function xml(text: string): string {
  return text
    .replace(INVALID_XML, '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
}

function columnName(index: number): string {
  let name = ''
  for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) {
    name = String.fromCharCode(65 + ((n - 1) % 26)) + name
  }
  return name
}

/** Nome de aba aceito pelo Excel: até 31 caracteres, sem `[]:*?/\`. */
export function sheetName(title: string): string {
  const clean = title.replace(/[[\]:*?/\\]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 31).trim()
  return clean === '' ? 'Planilha' : clean
}

interface Styles {
  xml: string
  /** Índice do estilo de célula por código de formato (`''` = cabeçalho). */
  index: Map<string, number>
}

/** Estilos: 0 padrão, 1 cabeçalho em negrito e um por formato de data ou número em uso. */
function buildStyles(formats: readonly string[]): Styles {
  const index = new Map<string, number>([['', 1]])
  const numFmts: string[] = []
  const xfs = [
    '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>',
    '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>',
  ]
  formats.forEach((code, i) => {
    const id = 164 + i
    numFmts.push(`<numFmt numFmtId="${id}" formatCode="${xml(code)}"/>`)
    index.set(code, xfs.length)
    xfs.push(`<xf numFmtId="${id}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`)
  })
  return {
    index,
    xml:
      '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
      '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
      (numFmts.length > 0 ? `<numFmts count="${numFmts.length}">${numFmts.join('')}</numFmts>` : '') +
      '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>' +
      '<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>' +
      '<fills count="2"><fill><patternFill patternType="none"/></fill>' +
      '<fill><patternFill patternType="gray125"/></fill></fills>' +
      '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
      '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
      `<cellXfs count="${xfs.length}">${xfs.join('')}</cellXfs>` +
      '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
      '</styleSheet>',
  }
}

/** O código de formato de uma célula, ou `null` para o padrão. */
function cellFormat(cell: ListExportCell, column: ListExportColumn): string | null {
  if (cell === null || cell.kind === 'text') return null
  if (cell.kind === 'date') return cell.time ? DATE_TIME_FORMAT : DATE_FORMAT
  return excelNumberFormat(column.numberFormat)
}

/** Largura aproximada da coluna em caracteres, entre 10 e 60. */
function columnWidth(column: ListExportColumn, cells: ListExportCell[]): number {
  let widest = column.label.length
  for (const cell of cells) {
    if (cell === null) continue
    const length =
      cell.kind === 'text' ? cell.value.length : cell.kind === 'date' ? (cell.time ? 16 : 10) : 14
    if (length > widest) widest = length
  }
  return Math.min(60, Math.max(10, widest + 2))
}

function buildSheet(table: ListExportTable, styles: Styles, strings: (text: string) => number): string {
  const rows: string[] = []
  const header = table.columns
    .map((column, c) => `<c r="${columnName(c)}1" t="s" s="1"><v>${strings(column.label)}</v></c>`)
    .join('')
  rows.push(`<row r="1">${header}</row>`)
  table.rows.forEach((row, r) => {
    const ref = r + 2
    const cells = row
      .map((cell, c) => {
        if (cell === null) return ''
        const at = `${columnName(c)}${ref}`
        const column = table.columns[c] as ListExportColumn
        const format = cellFormat(cell, column)
        const style = format === null ? '' : ` s="${styles.index.get(format) ?? 0}"`
        if (cell.kind === 'text') return `<c r="${at}" t="s"><v>${strings(cell.value)}</v></c>`
        const value = cell.kind === 'number' ? cell.value : excelSerial(cell.value)
        if (!Number.isFinite(value)) return ''
        return `<c r="${at}"${style}><v>${value}</v></c>`
      })
      .join('')
    rows.push(`<row r="${ref}">${cells}</row>`)
  })
  const cols = table.columns
    .map((column, c) => {
      const width = columnWidth(column, table.rows.map((row) => row[c] ?? null))
      return `<col min="${c + 1}" max="${c + 1}" width="${width}" customWidth="1"/>`
    })
    .join('')
  return (
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
    '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
    '<sheetViews><sheetView workbookViewId="0">' +
    '<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>' +
    '</sheetView></sheetViews>' +
    (cols !== '' ? `<cols>${cols}</cols>` : '') +
    `<sheetData>${rows.join('')}</sheetData>` +
    '</worksheet>'
  )
}

/** Gera o `.xlsx` da tabela. */
export function renderXlsx(table: ListExportTable): Uint8Array {
  const formats = new Set<string>()
  table.rows.forEach((row) =>
    row.forEach((cell, c) => {
      const format = cellFormat(cell, table.columns[c] as ListExportColumn)
      if (format !== null) formats.add(format)
    }),
  )
  const styles = buildStyles([...formats])

  const shared: string[] = []
  const sharedIndex = new Map<string, number>()
  const strings = (text: string): number => {
    const known = sharedIndex.get(text)
    if (known !== undefined) return known
    const index = shared.length
    shared.push(text)
    sharedIndex.set(text, index)
    return index
  }
  const sheet = buildSheet(table, styles, strings)
  const sharedXml =
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
    `<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${shared.length}" uniqueCount="${shared.length}">` +
    // `xml:space` preserva espaços nas pontas, que o Excel descartaria.
    shared.map((text) => `<si><t xml:space="preserve">${xml(text)}</t></si>`).join('') +
    '</sst>'

  return zip([
    [
      '[Content_Types].xml',
      '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
        '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
        '<Default Extension="xml" ContentType="application/xml"/>' +
        '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
        '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' +
        '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
        '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' +
        '</Types>',
    ],
    [
      '_rels/.rels',
      '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
        '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
        '</Relationships>',
    ],
    [
      'xl/workbook.xml',
      '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' +
        'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
        `<sheets><sheet name="${xml(sheetName(table.title))}" sheetId="1" r:id="rId1"/></sheets>` +
        '</workbook>',
    ],
    [
      'xl/_rels/workbook.xml.rels',
      '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
        '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
        '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
        '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' +
        '</Relationships>',
    ],
    ['xl/styles.xml', styles.xml],
    ['xl/sharedStrings.xml', sharedXml],
    ['xl/worksheets/sheet1.xml', sheet],
  ])
}

// =============================================================================
// ZIP
// =============================================================================

const CRC_TABLE = (() => {
  const table = new Uint32Array(256)
  for (let n = 0; n < 256; n += 1) {
    let c = n
    for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
    table[n] = c >>> 0
  }
  return table
})()

function crc32(bytes: Uint8Array): number {
  let crc = 0xffffffff
  for (const byte of bytes) crc = (CRC_TABLE[(crc ^ byte) & 0xff] as number) ^ (crc >>> 8)
  return (crc ^ 0xffffffff) >>> 0
}

// Data fixa (01/01/1980, a primeira do formato): o mesmo conteúdo gera os mesmos bytes.
const DOS_TIME = 0
const DOS_DATE = (0 << 9) | (1 << 5) | 1

/** ZIP com compressão deflate, o pacote que o formato XLSX exige. */
function zip(entries: Array<[name: string, content: string]>): Uint8Array {
  const encoder = new TextEncoder()
  const locals: Uint8Array[] = []
  const centrals: Uint8Array[] = []
  let offset = 0
  for (const [name, content] of entries) {
    const nameBytes = encoder.encode(name)
    const raw = encoder.encode(content)
    const data = new Uint8Array(deflateRawSync(raw))
    const crc = crc32(raw)

    const local = new Uint8Array(30 + nameBytes.length)
    const lv = new DataView(local.buffer)
    lv.setUint32(0, 0x04034b50, true)
    lv.setUint16(4, 20, true)
    lv.setUint16(6, 0x0800, true) // nomes em UTF-8
    lv.setUint16(8, 8, true) // deflate
    lv.setUint16(10, DOS_TIME, true)
    lv.setUint16(12, DOS_DATE, true)
    lv.setUint32(14, crc, true)
    lv.setUint32(18, data.length, true)
    lv.setUint32(22, raw.length, true)
    lv.setUint16(26, nameBytes.length, true)
    lv.setUint16(28, 0, true)
    local.set(nameBytes, 30)

    const central = new Uint8Array(46 + nameBytes.length)
    const cv = new DataView(central.buffer)
    cv.setUint32(0, 0x02014b50, true)
    cv.setUint16(4, 20, true)
    cv.setUint16(6, 20, true)
    cv.setUint16(8, 0x0800, true)
    cv.setUint16(10, 8, true)
    cv.setUint16(12, DOS_TIME, true)
    cv.setUint16(14, DOS_DATE, true)
    cv.setUint32(16, crc, true)
    cv.setUint32(20, data.length, true)
    cv.setUint32(24, raw.length, true)
    cv.setUint16(28, nameBytes.length, true)
    cv.setUint32(42, offset, true)
    central.set(nameBytes, 46)

    locals.push(local, data)
    centrals.push(central)
    offset += local.length + data.length
  }
  const centralSize = centrals.reduce((sum, part) => sum + part.length, 0)
  const end = new Uint8Array(22)
  const ev = new DataView(end.buffer)
  ev.setUint32(0, 0x06054b50, true)
  ev.setUint16(8, entries.length, true)
  ev.setUint16(10, entries.length, true)
  ev.setUint32(12, centralSize, true)
  ev.setUint32(16, offset, true)

  const parts = [...locals, ...centrals, end]
  const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))
  let at = 0
  for (const part of parts) {
    out.set(part, at)
    at += part.length
  }
  return out
}
