import * as React from 'react'
import * as PropTypes from 'prop-types'
import Head from 'next/head'
import unified from 'unified'
import parse from 'remark-parse'
import remark2react from 'remark-react'
import docgen from '../../docgen.json'

const propTypes = {
  of: PropTypes.string,
}

type Props = PropTypes.InferProps<typeof propTypes>

const Header: React.FC<Props> = ({ of: ofAttr }) => {
  const docs = docgen.find(d => d.displayName === ofAttr)

  if (!docs) {
    return null
  }

  const description = unified()
    .use(parse)
    .use(remark2react)
    .processSync(docs.description).result as any

  const [firstDescriptionChild] = description.props.children

  const summary = typeof firstDescriptionChild as unknown === 'string'
    ? firstDescriptionChild
    : firstDescriptionChild.props.children[0]

  return (
    <React.Fragment>
      <Head>
        <title>
          {docs.displayName} | {process.env.NEXT_PUBLIC_APP_TITLE}
        </title>
        <meta name="description" content={summary} key="description" />
      </Head>
      <h1>{docs.displayName}</h1>
      {description}
    </React.Fragment>
  )
}

Header.propTypes = propTypes

export default Header
