import { useEffect, useState } from 'react'

import { Box } from '../box'
import { omitThemingProps, useStyleConfig } from '../core'
import { ListItem } from '../list'
import { cs } from '../utils'
import { AccordionItemProps } from './accordion.types'
import AccordionItemArrow from './accordionItemArrow'
import { useAccordionContext } from './context'

/** An accordion item. */
export const AccordionItem = (props: AccordionItemProps) => {
  const {
    className,
    children,
    collapsed,
    content,
    disabled,
    id,
    iconPosition = 'end',
    title,
    onToggle,
    ...rest
  } = omitThemingProps(props)
  const [collapsedInternal, setIsCollapsedInternal] = useState<boolean>(false)
  const styles = useStyleConfig('Accordion', useAccordionContext())

  useEffect(() => {
    setIsCollapsedInternal(!!collapsed)
  }, [collapsed])

  const toggle = () => {
    if (!disabled) {
      onToggle?.({ id, collapsed: !collapsedInternal })
      setIsCollapsedInternal(!collapsedInternal)
    }
  }

  const isIconStart = iconPosition === 'start'
  const isIconEnd = iconPosition === 'end'

  return (
    <ListItem
      borderBottom="1px solid transparent"
      borderColor={styles.item.borderColor}
      className={cs('vui-accordion-item', className)}
      color="yellow"
      disabled={disabled}
      disabledBg={styles.item.disabledBg}
      disabledColor={styles.item.disabledColor}
      flexDirection="column"
      h="auto"
      id={`${id}`}
      p={0}
      w="100%"
      {...rest}
    >
      <Box
        center
        color="yellow"
        cursor={disabled ? 'not-allowed' : 'pointer'}
        hoverBg={
          disabled
            ? 'transparent'
            : collapsedInternal
              ? styles.item.itemTitleHoverBg
              : styles.item.expandedItemTitleHoverBg
        }
        justifyContent={iconPosition === 'start' ? 'initial' : 'space-between'}
        onClick={toggle}
        px={2}
        w="100%"
        {...styles.item}
      >
        {isIconStart && (
          <Box>
            <AccordionItemArrow collapsed={collapsedInternal} color={styles.icon.color} />
          </Box>
        )}
        <Box
          fontWeight={typeof title === 'string' ? '500' : 'inherit'}
          ml={isIconStart ? 2 : 0}
          opacity={disabled ? 0.5 : 1}
        >
          {title}
        </Box>
        {isIconEnd && (
          <Box>
            <AccordionItemArrow collapsed={collapsedInternal} color={styles.icon.color} disabled={disabled} />
          </Box>
        )}
      </Box>
      {!collapsedInternal && (
        <Box mb={2} mt={2} px={2} py={1} w="100%">
          {children ?? content}
        </Box>
      )}
    </ListItem>
  )
}

AccordionItem.displayName = 'AccordionItem'

export default AccordionItem
