'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'motion/react'
import { PlusIcon } from 'lucide-react'

interface AccordionItemProps {
    question: string
    answer: string
    isOpen: boolean
    onToggle: () => void
}

function AccordionItem({ question, answer, isOpen, onToggle }: AccordionItemProps) {
    return (
        <div className="rounded-xl border border-border bg-card overflow-hidden">
            <button
                onClick={ onToggle }
                className="flex w-full cursor-pointer items-center justify-between p-4 text-left"
            >
                <span className="font-medium text-base leading-snug tracking-tight text-base-content">
                    { question }
                </span>
                <motion.div
                    animate={{ rotate: isOpen ? 135 : 0 }}
                    transition={{ duration: 0.2, ease: [0.25, 0.1, 0.25, 1] }}
                >
                    <PlusIcon className="size-5 text-base-content" />
                </motion.div>
            </button>
            <AnimatePresence initial={ false }>
                { isOpen && (
                    <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
                        className="overflow-hidden"
                    >
                        <div className="border-t border-border p-4">
                            <p className="text-base leading-snug tracking-tight text-muted">
                                { answer }
                            </p>
                        </div>
                    </motion.div>
                ) }
            </AnimatePresence>
        </div>
    )
}

interface AccordionProps {
    items: { question: string; answer: string }[]
}

export function Accordion({ items }: AccordionProps) {
    const [openIndex, setOpenIndex] = useState<number | null>(null)

    const handleToggle = (index: number) => {
        setOpenIndex(openIndex === index ? null : index)
    }

    return (
        <>
            { items.map((item, index) => (
                <AccordionItem
                    key={ item.question }
                    question={ item.question }
                    answer={ item.answer }
                    isOpen={ openIndex === index }
                    onToggle={ () => handleToggle(index) }
                />
            )) }
        </>
    )
}
