import Excel from 'exceljs'

import ICON_NAVIGATION_SEARCH from './navigation-search.svg'

const { h, register, matter, preactHooks } = globalThis.ami
const { Box, Button, Form, Input, Table } = matter
const { useState, useEffect } = preactHooks

function SKDSSearch ({ src }) {
  const [data, setData] = useState()
  const [inputValue, setInputValue] = useState('')

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

  useEffect(() => {
    (async function () {
      const res = await fetch(src)
      const buf = await res.arrayBuffer()

      const workbook = new Excel.Workbook()
      await workbook.xlsx.load(buf)
      setData({ all: processWorksheets(workbook.worksheets), filtered: [], query: null })
    })().catch(console.error)
  }, [src])

  if (!data) {
    return null
  }

  return h(Box, { className: 'bg-bga text-txa rounded-2xl' },
    h(Form, {
      onSubmit: event => {
        event.preventDefault()
        const query = inputValue.trim()
        const filtered = data.all.filter(row => row.BRN === query)
        setData({ all: data.all, filtered, query })
      }
    },
    h('div', { className: 'flex gap-5' },
      h('div', { className: 'grow' },
        h(Input, {
          placeholder: 'Enter your BRN',
          type: 'search',
          value: inputValue,
          onInput: e => setInputValue(e.target.value)
        })
      ),
      h('div', { className: 'grow-0' },
        h(Button, {
          type: 'submit',
          _textless: true,
          _model: {
            name: 'Search',
            title: 'Search',
            icon: ICON_NAVIGATION_SEARCH
          }
        })
      ))
    ),
    data.query !== null && data.filtered.length === 0 && h('p', 'No records found.'),
    data.filtered.length > 0 && [
      h('p', `Found ${data.filtered.length} record(s).`),
      h(Table,
        h('tr', Object.keys(data.all[0]).map(key =>
          h('th', key)
        )),
        data.filtered.map(row =>
          h('tr', Object.values(row).map(value =>
            h('td', value)
          ))
        )
      )
    ]
  )
}

function processWorksheets (worksheets) {
  if (worksheets.length < 1) {
    throw new Error('No sheets found in the document.')
  }

  const data = []
  let headers
  for (const row of worksheets[0]._rows) {
    if (row.number === 1) {
      headers = row._cells.map(cell => cell.value)
      continue
    }

    const obj = row._cells.reduce((acc, cell, ii) => {
      acc[headers[ii]] = cell.value?.toString?.()?.trim?.()
      return acc
    }, {})

    data.push(obj)
  }
  return data
}

register(SKDSSearch, 'skds-search')
