import * as React from 'react'
import styled from 'styled-components'
import Highlight, { defaultProps } from 'prism-react-renderer'
import PrismTheme from '../../utilities/prism-themes/dark'

const Base = styled('figure')({
  margin: 0,
})

const Title = styled('figcaption')({
  textTransform: 'uppercase',
  fontWeight: 'bolder',
  fontSize: '0.75rem',
})

const CodeBlock = ({ children }) => {
  const { props, } = children
  const { children: code, className, metastring } = props
  const language = typeof className as string === 'string' ? className.split('-')[1] : 'plain'
  const meta = (typeof metastring as string === 'string' && metastring.length > 0)
    ? (metastring as string)
      .split(' ')
      .reduce(
        (m, s) => {
          const [key, value = ''] = s.split('=')
          if (value.trim().length > 0) {
            return {
              ...m,
              [key.trim()]: value.trim(),
            }
          }
          return {
            ...m,
            [key.trim()]: true,
          }
        },
        {}
      )
    : {}
  const prismInstance = defaultProps.Prism
  prismInstance.languages['yarnrc'] = {
    'attr-name': {
      pattern: /^[^\s#]+\s/,
    }
  }
  return (
    <Base>
      {
        meta['title'] && (
          <Title>
            {meta['title']}
          </Title>
        )
      }
      <Highlight
        Prism={prismInstance}
        language={language}
        code={(code as string).trim()}
        theme={PrismTheme}
      >
        {({ tokens, getLineProps, getTokenProps }) => (
          <pre>
            <code>
              {tokens.map((line, i) => (
                <React.Fragment>
                  {
                    i > 0 && <br />
                  }
                  <span {...getLineProps({ line, key: i })}>
                    {line.map((token, key) => (
                      <span {...getTokenProps({ token, key })} />
                    ))}
                  </span>
                </React.Fragment>
              ))}
            </code>
          </pre>
        )}
      </Highlight>
    </Base>
  )
}

export default CodeBlock
