import React, { Context, useContext } from 'react'
import useTheme from '../use-theme'
import FlyoutMenu from './flyout-menu'
import FlyoutMenuGroup from './flyout-menu-group'
import FlyoutMenuFooter from './flyout-menu-footer'
import FlyoutAction from './flyout-action'

interface Props {
  context: Context<any>
  icon?: React.ReactNode
  className?: string
}

const defaultProps = {
  className: ''
}

type ItemProps = {
  label: string
  active: boolean
  icon?: React.ReactNode
  onToggle?: (newPanel: string | undefined) => void
  onBreadcrumbClick: () => void
  promos: [JSX.Element]
}

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

const Flyout: React.FC<React.PropsWithChildren<FlyoutProps>> = ({
  children,
  context,
  icon,
  className,
  ...props
}) => {
  const theme = useTheme()
  const ctx: any = useContext(context)
  const open = ctx.openPanel.get
  const hasOpenPanel = open !== null && open !== 'root'
  return (
    <ul className={className + (hasOpenPanel ? ' active' : '')} {...props}>
      {React.Children.map(
        children as [React.ReactElement<ItemProps>],
        (child: React.ReactElement<ItemProps>) => {
          return React.cloneElement(child, {
            active: open === child.props.label ? true : undefined,
            onToggle: ctx.toggleNavItem,
            icon: icon
            // onBreadcrumbClick: () => ctx.openPanel.set('root')
          })
        }
      )}
      <style jsx>{`
        ul {
          align-items: center;
          margin: 0;
          padding: 0;
        }

        ul :global(li) {
          margin-bottom: 0;
        }
        ul :global(li::before) {
          display: none;
        }

        ul.active > :global(li) > :global(button) > :global(svg) {
          display: none;
        }
        ul > :global(li) > :global(button) > :global(svg) {
          display: block;
        }

        @media (min-width: ${theme.layout.breakpointMobile}) {
          ul {
            display: flex;
          }
          ul.active > :global(li) > :global(button) > :global(svg) {
            display: block;
          }
        }
      `}</style>
    </ul>
  )
}

type MemoPageComponent<P> = React.NamedExoticComponent<P> & {
  Action: typeof FlyoutAction
  Menu: typeof FlyoutMenu
  MenuGroup: typeof FlyoutMenuGroup
  MenuFooter: typeof FlyoutMenuFooter
}
type ComponentProps = Partial<typeof defaultProps> &
  Omit<Props, keyof typeof defaultProps> &
  NativeAttrs

Flyout.defaultProps = defaultProps

export default React.memo(Flyout) as MemoPageComponent<ComponentProps>
