import { CSSProperties, ReactNode } from 'react'
import classNames from 'classnames'
import { CommonComponentProps } from '../../utils/types'
import { Icon } from '../icon/Icon'
import { Collapse } from '../collapse/Collapse'
import './Accordion.scss'

export interface AccordionItemProps extends CommonComponentProps {
  className?: string
  style?: CSSProperties
  children?: ReactNode
  title?: ReactNode
  icon?: ReactNode | ((active: boolean) => ReactNode)
  name?: any
  activeName?: any
  multiple?: boolean
  disabled?: boolean
  duration?: number
  onClick?: () => void
}

export function AccordionItem(props: AccordionItemProps) {
  const {
    className,
    style,
    children,
    title,
    icon,
    name,
    activeName,
    multiple,
    disabled,
    duration = 300,
    onClick,
    ...restProps
  } = props

  const handleClick = () => {
    if (!disabled) {
      onClick?.()
    }
  }

  const active = multiple ? activeName.includes(name) : name === activeName

  const itemClass = classNames(
    's-accordion-item',
    {
      's-accordion-item-active': active,
      's-accordion-item-disabled': disabled,
    },
    className
  )

  return (
    <div {...restProps} className={itemClass}>
      <div className="s-accordion-item-header" onClick={handleClick}>
        <div className="s-accordion-item-title">{title}</div>
        <div className="s-accordion-item-icon">
          {typeof icon === 'function'
            ? icon(active)
            : icon ?? (
                <Icon
                  className="s-accordion-item-arrow"
                  prefix="si"
                  name="down"
                ></Icon>
              )}
        </div>
      </div>
      <Collapse
        duration={duration}
        visible={active}
        className="s-accordion-item-wrapper"
      >
        <div className="s-accordion-item-content">{children}</div>
      </Collapse>
    </div>
  )
}

export default AccordionItem
