import * as React from "react"
import { Collapsible as CollapsiblePrimitive } from "@base-ui/react/collapsible"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "../core/cn"

interface AccordionItem {
  value: string
  trigger: React.ReactNode
  content: React.ReactNode
  disabled?: boolean
}

interface AccordionProps {
  items?: AccordionItem[]
  type?: "single" | "multiple"
  defaultValue?: string | string[]
  className?: string
  itemClassName?: string
  children?: React.ReactNode
}

function Accordion({ className, children, ...props }: React.ComponentProps<"div"> & AccordionProps) {
  return (
    <div data-slot="accordion" className={cn("divide-y divide-border", className)} {...props}>
      {children}
    </div>
  )
}

interface AccordionItemProps extends CollapsiblePrimitive.Root.Props {
  className?: string
}

function AccordionItem({ className, ...props }: AccordionItemProps) {
  return (
    <CollapsiblePrimitive.Root
      data-slot="accordion-item"
      className={cn("group/accordion-item", className)}
      {...props}
    />
  )
}

function AccordionTrigger({ className, children, ...props }: CollapsiblePrimitive.Trigger.Props) {
  return (
    <CollapsiblePrimitive.Trigger
      data-slot="accordion-trigger"
      className={cn(
        "flex w-full items-center justify-between py-4 text-sm font-medium transition-all outline-none",
        "hover:underline focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:underline",
        "disabled:pointer-events-none disabled:opacity-50",
        "[&[data-open]>svg]:rotate-180",
        className
      )}
      {...props}
    >
      {children}
      <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform duration-200" />
    </CollapsiblePrimitive.Trigger>
  )
}

function AccordionContent({ className, children, ...props }: CollapsiblePrimitive.Panel.Props) {
  return (
    <CollapsiblePrimitive.Panel
      data-slot="accordion-content"
      className={cn(
        "overflow-hidden text-sm",
        "data-open:animate-in data-open:fade-in-0",
        "data-closed:animate-out data-closed:fade-out-0",
        className
      )}
      {...props}
    >
      <div className="pb-4">{children}</div>
    </CollapsiblePrimitive.Panel>
  )
}

export { Accordion, AccordionContent, AccordionItem, AccordionTrigger }
export type { AccordionItem as AccordionItemData, AccordionProps }
