import React from 'react'
import styled from 'styled-components'
import propTypes from 'prop-types'

export const defaultSize = 'md'
export const sizeVariants = {
  xxs: {
    fontSize: '10px',
    lineHeight: '14px',
  },
  xs: {
    fontSize: '12px',
    lineHeight: '18px',
  },
  sm: {
    fontSize: '14px',
    lineHeight: '20px',
  },
  md: {
    fontSize: '16px',
    lineHeight: '24px',
  },
  lg: {
    fontSize: '18px',
    lineHeight: '27px',
  },
} as const

type SizeKey = keyof typeof sizeVariants
type SizeProp = keyof typeof sizeVariants['xxs']

const sizes = Object.keys(sizeVariants) as SizeKey[]
export const getSize = ({ size = defaultSize }: { size?: SizeKey }) => sizeVariants[size] || sizeVariants.md

export const getFromSize = (prop: SizeProp, fallback = '') => ({ size }: { size?: SizeKey }) =>
  getSize({ size })[prop] ?? fallback

export const getVariableSize = ({
  size = defaultSize,
  shouldScaleFont,
}: {
  size?: SizeKey
  shouldScaleFont?: boolean
}) => {
  // protection against invalid size values
  size = sizeVariants[size] ? size : defaultSize
  // get the next size up.
  // if there is no larger size, stay the same size
  return shouldScaleFont ? sizeVariants[sizes[sizes.indexOf(size) + 1] || size] : sizeVariants[size] || sizeVariants.md
}
export const getFromVariableSize = (prop: SizeProp, fallback = '') => ({
  size,
  shouldScaleFont,
}: {
  size?: SizeKey
  shouldScaleFont?: boolean
}) => getVariableSize({ size, shouldScaleFont })[prop] ?? fallback

export type CopyProps = {
  bold?: boolean
  shouldScaleFont?: boolean
  light?: boolean
  size?: SizeKey
} & React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>

export const Copy = styled(({ bold, shouldScaleFont, light, ...props }: CopyProps) => <p {...props} />)`
  display: block;
  margin: 0;
  padding: 0;
  color: ${({ light, theme }) => (light ? theme.neutral400 : theme.neutral500)};
  font-family: postgrotesk, Roboto, Helvetica, sans-serif;
  font-size: ${getFromSize('fontSize')};
  font-weight: ${({ bold }) => (bold ? 'bold' : 'normal')};
  line-height: ${getFromSize('lineHeight')};

  strong {
    font-family: postgrotesk, Roboto, Helvetica, sans-serif;
  }

  @media (${({ theme }) => theme.forLargerThanPhone}) {
    font-size: ${getFromVariableSize('fontSize')};
    line-height: ${getFromVariableSize('lineHeight')};
  }
`
Copy.displayName = 'Copy'
Copy.propTypes = {
  bold: propTypes.bool,
  light: propTypes.bool,
  size: propTypes.oneOf(sizes),
  shouldScaleFont: propTypes.bool,
}
Copy.defaultProps = {
  size: defaultSize,
}

export default Copy
