"use client"

import { ChevronRight } from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import React, { useEffect, useState } from "react"

import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import {
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from "@/components/ui/sidebar"

export function SidebarSection({
  title,
  icon: Icon,
  items,
}: {
  title: string
  icon: React.ElementType
  items: { title: string; url: string }[] | undefined
}) {
  const pathname = usePathname()
  const isAnySubActive = items?.some((sub) => pathname.startsWith(sub.url))
  const [open, setOpen] = useState(isAnySubActive)

  useEffect(() => {
    setOpen(isAnySubActive)
  }, [isAnySubActive, pathname])

  return (
    <Collapsible
      className="group/collapsible w-full"
      open={open}
      onOpenChange={setOpen}
    >
      <SidebarMenuItem>
        <CollapsibleTrigger asChild>
          <SidebarMenuButton>
            <Icon className="mr-2 h-4 w-4" />
            <span>{title}</span>
            <ChevronRight className="ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90" />
          </SidebarMenuButton>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <SidebarMenuSub className="ml-4 flex flex-col gap-1">
            {items?.map((subItem, i) => {
              const isActive = pathname.startsWith(subItem.url)
              return (
                <SidebarMenuSubItem key={i}>
                  <SidebarMenuSubButton asChild isActive={isActive}>
                    <Link href={subItem.url}>{subItem.title}</Link>
                  </SidebarMenuSubButton>
                </SidebarMenuSubItem>
              )
            })}
          </SidebarMenuSub>
        </CollapsibleContent>
      </SidebarMenuItem>
    </Collapsible>
  )
}
