import FilteredData from '#amidala/wcs/shared/filtered-data/filtered-data.js'

const { h, register, matter } = globalThis.ami
const { Box, Table, Link } = matter

const LABELS = {
  notAvailable: 'N/A',
  text: 'Enter your search term',
  selectCountry: 'Country/Region',
  selectLanguage: 'Language',
  search: 'Search',
  download: 'Download',
  noResults: 'No results found. Please do not use wild card.'
}

const fields = [
  { key: 'productName', name: 'Name' },
  { key: 'country', name: 'Country/Region' },
  { key: 'language', name: 'Language' },
  { key: 'specId', name: 'Specification' },
  { key: 'cas', name: 'CAS' },
  { key: 'url', name: 'SDS URL', isUrl: true },
  { key: 'versionNumber', name: 'Version' }
]

// -----------------------------------------------------------------------------
// Filtered Data hooks & helpers
// -----------------------------------------------------------------------------

async function getData ({ src }) {
  try {
    const res = await fetch(src)
    if (!res.ok) {
      throw new Error(`Failed to load resource: ${src} (Status: ${res.status})`)
    }
    const json = await res.json()
    if (!json?.Items?.length) {
      throw new Error('Invalid JSON structure: missing or empty Items array')
    }
    return json.Items.map(item => {
      const {
        SequenceNumber: msdsId,
        ProductName: productName,
        /* LanguageCode */
        LanguageName: language,
        /* DocDescription */
        URL: url,
        SICC: siccCode,
        /* CountryCode */
        CAS: cas,
        NormedCAS: casNumberFormatted,
        NamSyn: synonyms,
        LanguageCountryDocType: languageCountry,
        SpecIdFull: specId,
        Version: versionNumber
      } = item

      const country = languageCountry?.split?.(';')?.[1]

      return {
        msdsId, productName, country, language, siccCode, url, cas, casNumberFormatted, synonyms, specId, versionNumber
      }
    }) || []
  } catch (error) {
    console.error('Error in getData:', error)
    throw error
  }
}

function naFormat (value) {
  return (value === null || value === undefined) ? LABELS.notAvailable : value
}

function Items ({ items }) {
  if (!items?.length) {
    return h('div', { className: 'text-center' }, LABELS.noResults)
  }

  return h(Box, { className: 'bg-bga text-txa rounded-2xl w-full overflow-x-auto' },
    h(Table,
      h('tr', fields.map(headerItem => h('th', headerItem.name))),
      items.map(
        result => h('tr', fields.map(
          field => {
            const fieldValue = result[field.key]
            return h('td', fieldValue && field.isUrl
              ? h(Link, {
                _variant: 'full',
                _model: {
                  name: LABELS.download,
                  value: fieldValue
                }
              })
              : naFormat(fieldValue))
          }
        ))
      )
    )
  )
}

// -----------------------------------------------------------------------------
// Main component, custom element definition
// -----------------------------------------------------------------------------

function MSDSSearch ({ src }) {
  return h(FilteredData, {
    getData,
    filters: [{
      type: 'text',
      label: LABELS.text,
      keys: ['productName', 'siccCode', 'synonyms', 'cas', 'casNumberFormatted', 'specId']
    }, {
      type: 'select',
      label: LABELS.selectCountry,
      keys: ['', 'country']
    }, {
      type: 'select',
      label: LABELS.selectLanguage,
      keys: ['', 'language']
    }],
    Items,
    src
  })
}

register(MSDSSearch, 'msds-search')
