import React from 'react'
import { FontLoader } from './FontLoader'
import { Grid } from './Grid'
import { CurrencyItem } from './CurrencyItem'
import { FormattedText } from './FormattedText'

export type Props = {
  start: boolean
  appData: VixonicData
  currencies: Currencies
}

export const App: React.FunctionComponent<Props> = (props) => {
  const { start, appData, currencies } = props
  const { parameters, downloadsPath } = appData
  const backgroundImage = parameters.backgroundImage?.filename
    ? `url("${downloadsPath}/${parameters.backgroundImage.filename}")`
    : ''

  if (!currencies || Object.keys(currencies).length === 0) {
    return <FormattedText text='No currencies available' format={parameters.nameFormat} />
  }

  const currencyItems: React.ReactNode[] = Object.values(currencies)
    .filter(currency => !!currency?.value)
    .map((currency: Currency) => {
      const displayName = currency.baseName || currency.baseCode || 'Currency'

      return (
        <CurrencyItem
          key={currency.baseCode + currency.targetCode}
          name={displayName}
          value={currency.value!}
          prefix={currency.targetPrefix || ''}
          suffix={currency.targetSuffix || ''}
          nameFormat={parameters.nameFormat || {}}
          valueFormat={parameters.valueFormat || {}}
          gap={parameters.internalElementsGap || 0}
        />
      )
    })

  return (
    <div style={{
      position: 'absolute',
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      backgroundImage,
      backgroundSize: '100% 100%',
      padding: parameters.padding || 0
    }}>
      <Grid
        id={'main'}
        items={currencyItems}
        style={{ height: '100%' }}
        border={{
          style: parameters.gridBorderStyle || 'none',
          width: parameters.gridBorderWidth || 0,
          color: parameters.gridBorderColor || 'transparent'
        }}
        layout={{
          rows: parameters.containerRows || 1,
          rowsGap: parameters.containerRowsGap || 0,
          columns: parameters.containerColumns || 1,
          columnsGap: parameters.containerColumnsGap || 0,
          alignment: {
            h: 'center',
            v: 'center'
          }
        }}
        animation={{
          mode: parameters.animationMode || 'fade',
          duration: (parameters.animationTime || 0) * 1000,
          speed: 2,
          reverse: parameters.animationOrder || false
        }}
        fontSize='10vh'
        animate={start}
      />
      <FontLoader paths={['nameFormat.font', 'valueFormat.font']} parameters={parameters} downloadsPath={downloadsPath} />
    </div>
  )
}
