import { Flex, Typography, Tag, Space } from 'antd'
import PropTypes from 'prop-types'

const { Text } = Typography

const getPrecision = (step) => {
  if (step == null) return null
  const stepStr = String(step)
  const dotIndex = stepStr.indexOf('.')
  return dotIndex === -1 ? 0 : stepStr.length - dotIndex - 1
}

const formatValue = (value, step) => {
  if (value == null || value === '') return null
  const parsed = parseFloat(value)
  if (Number.isNaN(parsed)) return null

  const precision = getPrecision(step)
  return precision == null ? parsed.toString() : parsed.toFixed(precision)
}

const MinMaxDisplay = ({ value, prefix = '', suffix = '', step }) => {
  const min = formatValue(value?.min, step)
  const max = formatValue(value?.max, step)

  return (
    <Flex gap={'middle'} align='center' style={{ height: '100%' }}>
      <Flex wrap>
        <Text style={{ marginRight: 4 }}>
          {min != null ? (
            prefix + min + suffix
          ) : (
            <Text type='secondary'>n/a</Text>
          )}
        </Text>
        <Space>
          <Tag>Min</Tag>
        </Space>
      </Flex>
      <Flex wrap>
        <Text style={{ marginRight: 4 }}>
          {max != null ? (
            prefix + max + suffix
          ) : (
            <Text type='secondary'>n/a</Text>
          )}
        </Text>
        <Space>
          <Tag>Max</Tag>
        </Space>
      </Flex>
    </Flex>
  )
}

MinMaxDisplay.propTypes = {
  value: PropTypes.shape({
    min: PropTypes.number,
    max: PropTypes.number
  }),
  prefix: PropTypes.string,
  suffix: PropTypes.string,
  step: PropTypes.number
}

export default MinMaxDisplay
