import React, { useEffect, useId, useState } from 'react'

export default function DocsFaqAccordion({ items, initialOpenIndex = 0, renderAnswer }) {
  const [openIndex, setOpenIndex] = useState(items.length > 0 ? initialOpenIndex : -1)
  const baseId = useId()

  useEffect(() => {
    setOpenIndex(items.length > 0 ? Math.min(initialOpenIndex, items.length - 1) : -1)
  }, [items.length, initialOpenIndex])

  return (
    <div className="space-y-3">
      {items.map((item, index) => {
        const buttonId = `${baseId}-button-${index}`
        const panelId = `${baseId}-panel-${index}`
        const isOpen = openIndex === index
        const answerContent = renderAnswer ? renderAnswer(item) : item.answer

        return (
          <div key={item.question} className="overflow-hidden rounded-[24px] border border-white/10 bg-black/20">
            <h3>
              <button
                id={buttonId}
                type="button"
                className="flex w-full items-center justify-between gap-4 px-4 py-4 text-left md:px-5"
                aria-expanded={isOpen}
                aria-controls={panelId}
                onClick={() => setOpenIndex(isOpen ? -1 : index)}
              >
                <span className="text-base font-semibold text-white">{item.question}</span>
                <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-slate-300">
                  <i className={`fa-solid ${isOpen ? 'fa-minus' : 'fa-plus'} text-xs`} />
                </span>
              </button>
            </h3>
            <div
              id={panelId}
              role="region"
              aria-labelledby={buttonId}
              className={isOpen ? 'block border-t border-white/10 px-4 py-4 md:px-5' : 'hidden'}
            >
              {typeof answerContent === 'string' ? (
                <p className="text-sm leading-7 text-slate-300">{answerContent}</p>
              ) : (
                <div className="space-y-4 text-sm leading-7 text-slate-300">{answerContent}</div>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}