import { Children, Fragment, useMemo } from 'react'

import { styled, useStyleConfig, vui, VuiComponent } from '../core'
import { cs, filterUndefined } from '../utils'
import { BreadcrumbsProps } from './breadcrumbs.types'
import BreadcrumbsItem from './breadcrumbsItem'
import BreadcrumbsSeparator from './breadcrumbsSeparator'
import { BreadcrumbsProvider } from './context'

export const BreadcrumbsBase = styled.divBox`
  display: flex;
  min-width: 0;
  transition-duration: normal;

  .vui-breadcrumbs-item:last-of-type {
    font-weight: 600;
  }
`

/** Breadcrumbs consist of a list of items that help a user visualize a page's location within the hierarchical structure of a website, and allow correspondent navigation. */
export const Breadcrumbs = vui<'div', BreadcrumbsProps>((props, ref) => {
  const { children, className, size, variant, ...rest } = props
  const styles = useStyleConfig('Breadcrumbs', props)
  const context = useMemo(() => filterUndefined({ size, variant }), [size, variant])
  const aliasedProps = filterUndefined<BreadcrumbsProps>({})
  const arrayChildren = Children.toArray(children)

  return (
    <BreadcrumbsProvider value={context}>
      <BreadcrumbsBase
        className={cs('vui-breadcrumbs', className)}
        ref={ref}
        {...styles.main}
        {...aliasedProps}
        {...rest}
      >
        {Children.map(arrayChildren, (child, key) => (
          <Fragment key={key}>
            {child}
            {key !== arrayChildren.length - 1 && <BreadcrumbsSeparator />}
          </Fragment>
        ))}
      </BreadcrumbsBase>
    </BreadcrumbsProvider>
  )
}) as VuiComponent<'div', BreadcrumbsProps> & {
  Item: typeof BreadcrumbsItem
}

Breadcrumbs.Item = BreadcrumbsItem
Breadcrumbs.displayName = 'Breadcrumbs'
export default Breadcrumbs
