import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
import React, { useState } from "react"
import { SvgUse } from "../../shared/SvgUse"

function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
  return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}

function CollapsibleTrigger({
  ...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
  return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
}

function CollapsibleContent({
  className,
  ...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
  return (
    <CollapsiblePrimitive.CollapsibleContent
      data-slot="collapsible-content"
      className={`overflow-hidden data-[state=closed]:animate-[slideUp_0.2s_ease-out] data-[state=open]:animate-[slideDown_0.2s_ease-out] ${className || ""}`}
      {...props}
    />
  )
}

// Automatic collapsible with built-in state management and chevron
function CollapsibleWithChevron({
  children,
  trigger,
  chevronClassName = "size-4",
  ...props
}: Omit<React.ComponentProps<typeof CollapsiblePrimitive.Root>, "open" | "onOpenChange"> & {
  trigger: React.ReactElement<any>
  chevronClassName?: string
}) {
  const [open, setOpen] = useState(false)

  // Add chevron to the trigger
  const triggerWithChevron = React.cloneElement(trigger, {
    ...trigger.props,
    children: (
      <>
        {trigger.props.children}
        <SvgUse icon={open ? "chevron-up" : "chevron-down"} className={chevronClassName} />
      </>
    ),
  })

  return (
    <Collapsible open={open} onOpenChange={setOpen} {...props}>
      <CollapsibleTrigger asChild>{triggerWithChevron}</CollapsibleTrigger>
      {children}
    </Collapsible>
  )
}

// Simple chevron icon component (for manual usage)
function ChevronIcon({
  open,
  className = "size-4",
}: Readonly<{ open: boolean; className?: string }>) {
  return <SvgUse icon={open ? "chevron-up" : "chevron-down"} className={className} />
}

export { Collapsible, CollapsibleTrigger, CollapsibleContent, CollapsibleWithChevron, ChevronIcon }
