import React, { useMemo } from 'react'
import useTheme from '../use-theme'
import withDefaults from '../utils/with-defaults'

const NavEntry: React.FC<React.PropsWithChildren<{ className?: string }>> = ({
  className,
  children
}) => {
  return (
    <li className={className}>
      {children}
      <style jsx>{`
        li {
          line-height: 2;
        }
        li.group-entry + li.group-entry {
          margin-top: 32px;
        }
      `}</style>
    </li>
  )
}

interface Props {
  className?: string
  label: string
}

const defaultProps = {
  className: ''
}

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

const FlyoutMenuGroup: React.FC<React.PropsWithChildren<FlyoutMenuGroupProps>> = ({
  label,
  children,
  ...props
}) => {
  const theme = useTheme()
  const listClass = useMemo(() => (label ? 'nav-entry' : 'group-entry'), [label])
  return (
    <div {...props}>
      {label && <span className="group-title">{label}</span>}
      <ul className="group-list">
        {React.Children.map(
          children as [React.ReactElement<any>],
          (child: React.ReactElement<any>) => {
            return <NavEntry className={listClass}>{React.cloneElement(child)}</NavEntry>
          }
        )}
      </ul>
      <style jsx>{`
        .group-list,
        .group-list :global(ul) {
          list-style-type: none;
          padding: 0;
          margin: 0;
        }
        .group-list > :global(li) > :global(a),
        .group-list > :global(li) > :global(button) {
          display: flex;
          align-items: center;
        }

        .group-title {
          color: ${theme.palette.secondary};
          display: block;
          margin: 32px 0 12px;
          font-weight: 500;
          font-size: 0.75rem;
          letter-spacing: 0.08em;
          line-height: 1.5em;
          text-transform: uppercase;
        }

        @media (min-width: ${theme.layout.breakpointMobile}) {
          div {
            min-width: 160px;
          }
          .group-title {
            display: block;
            color: inherit;
            margin: 0 0 16px;
          }
          div + div {
            margin-left: 64px;
          }
        }
      `}</style>
    </div>
  )
}

export default withDefaults(FlyoutMenuGroup, defaultProps)
