import * as React from 'react'
import Link from 'next/link'
import { MDXProvider } from '@mdx-js/react'
import Head from 'next/head'
import styled from 'styled-components'
import sidebar from '../sidebar.json'
import brand from '../../brand'
import Sidebar from '../components/Sidebar/Sidebar'
import pkg from '../../../../package.json'
import CodeBlock from '../components/CodeBlock/CodeBlock'

const Container = styled('div')({
  '@media only screen': {
    maxWidth: 720,
    margin: '0 auto',
    padding: '0 1rem',
    boxSizing: 'border-box',
  },
})

const Main = styled('main')({
  '@media only screen': {
    margin: '4rem 0',
  },
})

type AppProps = {
  Component: React.ElementType,
  pageProps: Record<string, unknown>,
}

const App: React.FC<AppProps> = ({
  Component,
  pageProps,
}) => (
  <React.Fragment>
    <Head>
      <title>{pkg['title'] || pkg.name}</title>
      <meta name="description" content={pkg.description} key="description" />
    </Head>
    <Sidebar
      brand={brand}
      data={sidebar}
      initialTheme="Dark"
    />
    <Main>
      <Container>
        <MDXProvider
          components={{
            a: ({ href, children, ...etcProps }) => {
              if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//')) {
                return (
                  <a
                    {...etcProps}
                    href={href}
                    target="_blank"
                    rel="noreferrer noopener"
                  >
                    {children}
                  </a>
                )
              }
              return (
                <Link
                  href={href}
                  passHref
                  {...etcProps}
                >
                  <a>
                    {children}
                  </a>
                </Link>
              )
            },
            pre: CodeBlock,
          }}
        >
          <Component
            {...pageProps}
          />
        </MDXProvider>
      </Container>
    </Main>
  </React.Fragment>
)

export default App
