import React, { CSSProperties } from 'react'

const alignments = {
  center: 'center',
  left: 'flex-start',
  right: 'flex-end'
}

type Aligment = {
  horizontal: keyof typeof alignments,
  vertical: keyof typeof alignments
}

interface Props {
  format?: any
  lineHeight?: number
  maxChar?: number
  style?: CSSProperties
  text: string
  unit?: string
  paddingBottom?: string
  paddingTop?: string
}

export const FormattedText: React.FunctionComponent<Props> = ({ text, format, maxChar, lineHeight, style, unit, paddingBottom, paddingTop }) => {
  const trimText = (text: any, maxChar: any) => {
    const isValid = maxChar && maxChar >= 3
    if (isValid && (text && text.length > maxChar)) {
      const returnText = text.substring(0, maxChar - 3)
      returnText.substr(-1, 3)
      return `${returnText.trim()}...`
    }
    return text
  }

  const checkNested = (obj: any, path: string): boolean => {
    return path.split('.').every(segment => {
      if (obj?.hasOwnProperty(segment)) {
        obj = obj[segment]
        return true
      }
      return false
    })
  }

  const getHorizontalAlignment = (alignment: Aligment) => {
    if (alignment) {
      const hA = alignment.horizontal
      return alignments.hasOwnProperty(hA) ? alignments[alignment.horizontal] : 'flex-start'
    }
    return 'flex-start'
  }

  const renderText = maxChar ? trimText(text, maxChar) : text
  const containerStyle = {
    display: 'inline-flex',
    justifyContent: getHorizontalAlignment(format.alignment),
    ...style
  }

  return (
    <div style={containerStyle}>
      <span style={{
        color: format?.fontColor,
        fontFamily: checkNested(format, 'font.filename') ? `'${format?.font?.filename?.replace('.', '-')}'` : '',
        fontSize: `${format?.fontSize}${unit}`,
        textAlign: checkNested(format, 'alignment.horizontal') ? format?.alignment?.horizontal : 'left',
        lineHeight: lineHeight,
        paddingBottom: paddingBottom,
        paddingTop: paddingTop,
        display: 'inline-flex'
      }}>{renderText}</span>
    </div>
  )
}

FormattedText.defaultProps = {
  format: {},
  lineHeight: 1,
  unit: 'vh',
  maxChar: undefined
}
