import React from 'react'
import PropTypes from 'prop-types'
import { StackView, Typography, useCopy } from '@telus-uds/components-base'
import styled from 'styled-components'
import dictionary from './dictionary'
import { countdownVariantPropType, dictionaryContentShape } from './types'
// !TODO: put this back
import { SEGMENT_WIDTH_TO_FONT_SIZE_RATIO } from './constants'

// Pads with zeros on the left if it's a single digit number
const pad = (number, segmentWidth = 2) => String(number).padStart(segmentWidth, '0')

const Container = styled.div(({ segmentFontSize, segmentWidth = 2, variant: { feature } }) => ({
  justifyContent: 'space-evenly',
  display: 'inline-flex',
  ...(feature && {
    // This is required because when the numbers for Countdown change, the character widths will change and thereby effecting the container demensions.
    width: `${segmentFontSize * SEGMENT_WIDTH_TO_FONT_SIZE_RATIO * segmentWidth}px`,
    display: 'flex'
  })
}))
// A segment of the countdown string: we need to make sure it
// keeps its width constant to prevent the whole component from
// being automatically resized while using variable size fonts
const Segment = React.forwardRef(
  (
    {
      copy = 'en',
      segmentFontSize,
      labelKey,
      labelTokens,
      number,
      numberTokens,
      labelMediaIds,
      mainTextMediaIds,
      segmentWidth = 2,
      variant = {}
    },
    ref
  ) => {
    const getCopy = useCopy({ dictionary, copy })
    const { label, large, feature } = variant

    return (
      <Container
        segmentFontSize={segmentFontSize}
        segmentWidth={segmentWidth}
        variant={variant}
        ref={ref}
      >
        <StackView
          direction={large || feature ? 'column' : 'row'}
          space={large || feature ? 0 : 1}
          tokens={{ alignItems: 'center' }}
        >
          <Typography
            tokens={numberTokens}
            media={mainTextMediaIds}
            dataSet={{ chromatic: labelKey === 'second' ? 'ignore' : undefined }}
          >
            {pad(number, segmentWidth)}
          </Typography>
          {label && (
            <Typography tokens={labelTokens} media={labelMediaIds}>
              {getCopy(number === 1 ? labelKey : `${labelKey}s`)}
            </Typography>
          )}
        </StackView>
      </Container>
    )
  }
)

Segment.displayName = 'Segment'

Segment.propTypes = {
  /**
   * Copy language identifier or a dictionary instance.
   */
  copy: PropTypes.oneOfType([PropTypes.oneOf(['en', 'fr']), dictionaryContentShape]),
  segmentFontSize: PropTypes.number,
  labelKey: PropTypes.oneOf(['day', 'hour', 'minute', 'second']),
  labelTokens: PropTypes.object,
  number: PropTypes.number,
  numberTokens: PropTypes.object,
  segmentWidth: PropTypes.number,
  labelMediaIds: PropTypes.string,
  mainTextMediaIds: PropTypes.string,
  variant: countdownVariantPropType
}

export default Segment
