import React, { useMemo } from 'react'

import { styled, useStyleConfig, vui, VuiComponent } from '../core'
import List from '../list'
import { cs, filterUndefined } from '../utils'
import { AccordionItemProps, AccordionProps } from './accordion.types'
import AccordionItem from './accordionItem'
import AccordionItemHorizontal from './accordionItemHorizontal'
import { AccordionProvider } from './context'

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

/** Allows to show and hide sections of related content on a page. */
export const Accordion = vui<'div', AccordionProps>((props, ref) => {
  const { children, className, items, orientation = 'vertical', iconPosition = 'end', size, variant, ...rest } = props
  const styles = useStyleConfig('Accordion', props)
  const context = useMemo(() => filterUndefined({ size, variant }), [size, variant])
  const aliasedProps = filterUndefined<AccordionProps>({})
  const isVertical = orientation === 'vertical'
  return (
    <AccordionProvider value={context}>
      <AccordionBase
        borderLeft={
          isVertical
            ? undefined
            : `1px solid transparent
        `
        }
        borderTop={isVertical ? `1px solid transparent` : undefined}
        className={cs('vui-accordion', className)}
        ref={ref}
        w="100%"
        {...styles.container}
        {...aliasedProps}
        {...rest}
      >
        {isVertical ? (
          <List w="100%">
            {items
              ? items?.map?.((item: AccordionItemProps, key: number) => (
                  <AccordionItem iconPosition={iconPosition} key={key} {...item} />
                ))
              : children}
          </List>
        ) : items ? (
          items?.map?.((item: AccordionItemProps, key: number) => <AccordionItemHorizontal key={key} {...item} />)
        ) : (
          children
        )}
      </AccordionBase>
    </AccordionProvider>
  )
}) as VuiComponent<'div', AccordionProps> & {
  Item: typeof AccordionItem
  ItemHorizontal: typeof AccordionItemHorizontal
}

Accordion.Item = AccordionItem
Accordion.ItemHorizontal = AccordionItemHorizontal
Accordion.displayName = 'Accordion'

export default Accordion
