import React, { FC, memo } from 'react'
import { Text } from 'react-native'
import { dataTypes } from '@adalo/constants'

import { isEqual } from 'lodash'

import { formatDate, formatDateOnly, type Format } from 'utils/luxon/formatters'
import { CellProps } from './TableTypes'
import { styles } from './TableRow'

const DateCell: FC<CellProps> = memo(({ cell, theme }) => {
  const { binding } = cell

  let format

  if (binding) {
    format = binding.format
  }

  let formattedValue

  const style = [styles.cellText, theme.cellText]

  if (cell.value) {
    if (cell.type === dataTypes.DATE && format) {
      formattedValue = formatDate(cell.value as string, format as Format)

      return <Text style={style}>{formattedValue}</Text>
    }

    if (cell.type === dataTypes.DATE_ONLY && format) {
      formattedValue = formatDateOnly(cell.value as string, format as Format)

      return <Text style={style}>{formattedValue}</Text>
    }
  }

  return <Text style={style}>{cell?.value}</Text>
})

export default memo(DateCell, isEqual)
