import { useState } from 'react'
import type { ReactNode } from 'react'
import { Collapsible } from '../../primitives/Collapsible/Collapsible'
import styles from './Accordion.module.css'

export interface AccordionItem {
  id: string
  title: ReactNode
  content: ReactNode
  defaultOpen?: boolean
}

interface AccordionProps {
  items: AccordionItem[]
  multiple?: boolean
  className?: string
}

export function Accordion({ items, multiple = false, className }: AccordionProps) {
  const [openIds, setOpenIds] = useState<Set<string>>(() => {
    const initial = new Set<string>()
    for (const item of items) {
      if (item.defaultOpen) initial.add(item.id)
    }
    // In single mode, only keep the first defaultOpen item
    if (!multiple && initial.size > 1) {
      const first = [...initial][0]
      return new Set([first])
    }
    return initial
  })

  function handleToggle(id: string, open: boolean) {
    setOpenIds((prev) => {
      const next = new Set(prev)
      if (open) {
        if (!multiple) next.clear()
        next.add(id)
      } else {
        next.delete(id)
      }
      return next
    })
  }

  return (
    <div className={`${styles.root} ${className ?? ''}`}>
      {items.map((item, index) => {
        const isFirst = index === 0
        const isLast = index === items.length - 1
        const itemClass = [
          styles.item,
          isFirst ? styles.itemFirst : '',
          isLast ? styles.itemLast : '',
          index > 0 ? styles.itemDivider : '',
        ]
          .filter(Boolean)
          .join(' ')

        return (
          <Collapsible
            key={item.id}
            title={item.title}
            open={openIds.has(item.id)}
            onToggle={(open) => handleToggle(item.id, open)}
            className={itemClass}
          >
            {item.content}
          </Collapsible>
        )
      })}
    </div>
  )
}
