import React from 'react'
import { dataTypes } from '@adalo/constants'
import { CellProps } from './TableTypes'
import TextCell from './TextCell'
import NumberCell from './NumberCell'
import DateCell from './DateCell'
import LocationCell from './LocationCell'
import FileCell from './FileCell'
import ImageCell from './ImageCell'
import BooleanCell from './BooleanCell'

type DataType = typeof dataTypes[keyof typeof dataTypes]
type CellComponent = React.FC<CellProps> | React.ComponentClass<CellProps>
type CellComponentMap = Partial<{ [k in DataType]: CellComponent }>

const ComponentMap: CellComponentMap = {
  [dataTypes.TEXT]: TextCell,
  [dataTypes.NUMBER]: NumberCell,
  [dataTypes.DATE]: DateCell,
  [dataTypes.DATE_ONLY]: DateCell,
  [dataTypes.LOCATION]: LocationCell,
  [dataTypes.FILE]: FileCell,
  [dataTypes.IMAGE]: ImageCell,
  [dataTypes.BOOLEAN]: BooleanCell,
}

const TableCell: React.FC<CellProps> = props => {
  const { cell } = props
  const CellComponent = ComponentMap[cell.type]

  if (!CellComponent) {
    throw new Error(
      `Attempted to render table cell of unsupported type: ${cell.type}`
    )
  }

  return <CellComponent {...props} />
}

export default TableCell
