import React, { useMemo } from 'react'
import withDefaults from '../utils/with-defaults'
import Text from '../text'
import ArrowUpIcon from './arrow-up-icon'
import ArrowDownIcon from './arrow-down-icon'
import useTheme from '../use-theme'
import Skeleton from '../skeleton'

interface Props {
  value: number
  average: number
  unit?: string
  labelText?: string
  className?: string
  locale?: string
  loading: boolean
}

const defaultProps = {
  unit: '',
  labelText: '',
  className: '',
  locale: 'de-CH',
  loading: false
}

type NativeAttrs = Omit<React.HTMLAttributes<any>, keyof Props>
export type MetricCardFooterComponentProps = Props & typeof defaultProps & NativeAttrs

const MetricCardFooter: React.FC<MetricCardFooterComponentProps> = ({
  value,
  average,
  className,
  unit,
  labelText,
  locale,
  loading
}) => {
  const theme = useTheme()

  const { diff, positive } = useMemo(
    () => ({
      diff: Math.abs(value - average),
      positive: value - average > 0
    }),
    [value, average]
  )

  const footerText = useCardFooterText(diff, locale, unit)

  const valueColor = useMemo(
    () => (positive ? theme.palette.success : theme.palette.errorDark),
    [positive]
  )

  const footerContent = loading ? (
    <Text b>
      <Skeleton size="mini" />
    </Text>
  ) : (
    <>
      <Text b className="value">
        {footerText}
      </Text>
      {positive ? (
        <ArrowUpIcon color={theme.palette.success} size={12} />
      ) : (
        <ArrowDownIcon color={theme.palette.errorDark} size={12} />
      )}
      <Text span>&nbsp;{labelText}</Text>
    </>
  )

  return (
    <div className={`card-footer ${className}`}>
      {footerContent}
      <style jsx>{`
        .card-footer {
          margin-top: ${theme.layout.gap};
          margin-bottom: ${theme.layout.gapHalfNegative};
          padding-top: ${theme.layout.gapQuarter};
          border-top: 1px solid ${theme.palette.accents_2};
          display: flex;
          align-items: center;
          flex-direction: row;
          font-size: 0.875rem;
        }
        .card-footer :global(.value) {
          color: ${valueColor};
          font-weight: bold;
        }
      `}</style>
    </div>
  )
}

const useCardFooterText = (diff: number, locale: string, unit: string) =>
  useMemo(() => `${diff.toLocaleString(locale)} ${unit} `, [locale, unit, diff])

const MemoCardContent = React.memo(MetricCardFooter)

export default withDefaults(MemoCardContent, defaultProps)
