const { h, register, matter, preactHooks } = globalThis.ami
const { Box, Table, Link, Asset } = matter
const { useState, useEffect, useMemo } = preactHooks

function ComparisonChart ({ src, highlight }) {
  const [products, setProducts] = useState()

  if (!src) {
    console.error('Missing data source.')
    return null
  }

  useEffect(() => {
    (async () => {
      const res = await fetch(src)
      setProducts(await res.json())
    })().catch(console.error)
  }, [src])

  if (!Array.isArray(products) || products.length === 0) {
    return null
  }

  const rows = useMemo(() => Object.keys(products[0]), [products])
  const columnCount = useMemo(() => products.length + 1, [products])
  const highlightIndex = useMemo(() => Number.parseInt(highlight, 10) + 1, [highlight])

  return h(Box, { className: 'rounded-2xl bg-bga text-txa h-full p-6' },
    h(Table, {
      // Override styles to achieve custom look and feel of the table whilst retaining the basic table structure.
      _style: id => `
        ${id} tr > th, ${id} tr > td {
          vertical-align: middle;
        }
        ${id} tr > th[scope=col], ${id} tr > td {
          text-align: center
        }
        ${id} tr > th[scope=row], ${id} tr > td {
          width: calc(100% / ${columnCount});
        }
        ${id} tr:nth-child(2) > * {
          background-color: hsl(var(--color-txa));
          color: hsl(var(--color-bga));
          border-right: 1px solid hsla(var(--color-bga), 0.2);
        }
        ${id} tr:nth-child(3) > * {
          background-color: hsl(var(--color-bgb));
          color: hsl(var(--color-txb));
          border-right: 1px solid hsla(var(--color-txb), 0.2);
        }
        ${id} tr:nth-child(n + 4) > td {
          font-size: calc(20px * var(--font-scale));
          font-weight: 700;
        }
        ${id} tr > td:nth-child(${highlightIndex}) {
          border-right: 4px solid hsl(var(--color-txa));
          border-left: 4px solid hsl(var(--color-txa));
        }
        ${id} tr:first-child > td:nth-child(${highlightIndex}) {
          border-top: 4px solid hsl(var(--color-txa));
        }
        ${id} tr:last-child > td:nth-child(${highlightIndex}) {
          border-bottom: 4px solid hsl(var(--color-txa));
        }
      `,
      children: [
        h(ImageRow, { products }),
        h(Row, { products, index: 2, colScope: true }), // Name
        h(Row, { products, index: 3 }), // Type
        rows.slice(4).map((_name, ii) => h(Row, { products, index: ii + 4 }))
      ]
    })
  )
}

function ImageRow ({ products }) {
  return h('tr',
    h('td', ''),
    products.map(p => {
      const link = p['Product Link']
      return h('td',
        h(link ? Link : 'div', { className: 'block', _model: { value: link } },
          h(Asset, {
            _tall: true,
            _fit: 'contain',
            _model: {
              image: { src: p['Product Image'], alt: p['Product Name'] }
            }
          })
        )
      )
    })
  )
}

function Row ({ products, index, colScope = false }) {
  const rows = Object.keys(products[0])
  const name = rows[index]

  return colScope
    ? h('tr',
      h('th', { scope: 'row' }, name),
      products.map(p => h('th', { scope: 'col' }, p[name]))
    )
    : h('tr',
      h('th', { scope: 'row' }, name),
      products.map(p => h('td', p[name]))
    )
}

register(ComparisonChart, 'comparison-chart')
