import * as React from 'react'
import * as PropTypes from 'prop-types'
import Link from 'next/link'
import styled from 'styled-components'
import NavLink from '../NavLink/NavLink'

const Container = styled('span')({
  display: 'flex',
  alignItems: 'center',
  padding: '0 1rem',
  height: '100%',
  margin: '0 0 0 auto',
  boxSizing: 'border-box',
  '@media (min-width: 720px)': {
    maxWidth: 'var(--max-width)',
  },
})

const HeaderContainer = styled(Container)({
  marginTop: '2rem',
  fontSize: '0.75rem',
  fontWeight: 'bolder',
  textTransform: 'uppercase',
})

const propTypes = {
  data: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object,
    PropTypes.string,
  ])
}

type Props = PropTypes.InferProps<typeof propTypes>

const Nav: React.FC<Props> = ({
  data,
}) => {
  if (Array.isArray(data! as unknown[])) {
    return (
      <div>
        {
          (data as (string | object | null | undefined)[]).map(d => (
            <Nav
              key={JSON.stringify(d)}
              data={d}
            />
          ))
        }
      </div>
    )
  }
  if (typeof data as unknown === 'object') {
    const [entry] = Object.entries(data as Record<string, unknown>)
    const [key, value] = entry
    if (Array.isArray(value as unknown[])) {
      return (
        <div>
          <HeaderContainer>
            {key}
          </HeaderContainer>
          {
            (value as (string | object | null | undefined)[]).map(v => (
              <Nav
                key={JSON.stringify(v)}
                data={v}
              />
            ))
          }
        </div>
      )
    }
    return (
      <div>
        <Link
          href={value as string}
          passHref
        >
          {
            // @ts-ignore
            <NavLink
              href={value as string}
              title={key}
              enclosingComponent={Container}
            />
          }
        </Link>
      </div>
    )
  }
  return (
    <div>
      <Link
        href={data as string}
        passHref
      >
        {
          // @ts-ignore
          <NavLink
            href={data as string}
            title={data as string}
            enclosingComponent={Container}
          />
        }
      </Link>
    </div>
  )
}

Nav.propTypes = propTypes

export default Nav
