
'use client';

import * as React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { cn } from '@/lib/utils';
import { ChevronDown } from 'lucide-react';

interface CollapsibleMenuProps {
  item: {
    label: string;
    icon: React.ElementType;
    href?: string;
    subItems?: { href: string; label: string }[];
  };
  isExpanded: boolean;
}

export function CollapsibleMenu({ item, isExpanded }: CollapsibleMenuProps) {
  const pathname = usePathname();
  const [isOpen, setIsOpen] = React.useState(
    item.subItems?.some(sub => pathname.startsWith(sub.href)) || false
  );

  const isParentActive = !item.subItems && pathname === item.href;
  const isChildActive = item.subItems?.some(sub => pathname.startsWith(sub.href));

  if (!item.subItems) {
    return (
      <Link
        href={item.href!}
        className={cn(
          "flex items-center gap-3 rounded-md px-3 py-2 text-muted-foreground transition-all hover:text-primary",
          { "bg-muted text-primary": isParentActive },
          !isExpanded && "justify-center"
        )}
      >
        <item.icon className="h-5 w-5" />
        <span className={cn("flex-1", !isExpanded && "sr-only")}>{item.label}</span>
      </Link>
    );
  }

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <CollapsibleTrigger asChild>
        <button
          className={cn(
            "flex w-full items-center justify-between gap-3 rounded-md px-3 py-2 text-muted-foreground transition-all hover:text-primary",
            { "text-primary": isChildActive },
             !isExpanded && "justify-center"
          )}
        >
          <div className="flex items-center gap-3">
            <item.icon className="h-5 w-5" />
            <span className={cn("flex-1 text-left", !isExpanded && "sr-only")}>{item.label}</span>
          </div>
          <ChevronDown
            className={cn(
              "h-4 w-4 transition-transform",
              { "rotate-180": isOpen },
              !isExpanded && "hidden"
            )}
          />
        </button>
      </CollapsibleTrigger>
      <CollapsibleContent className={cn("py-1", isExpanded ? "pl-7" : "pl-0")}>
        <div className={cn("flex flex-col gap-1", !isExpanded && "items-center")}>
          {item.subItems.map((subItem) => (
            <Link
              key={subItem.label}
              href={subItem.href}
              className={cn(
                "rounded-md px-3 py-2 text-sm font-medium text-muted-foreground transition-all hover:text-primary",
                { "bg-muted text-primary": pathname.startsWith(subItem.href) }
              )}
            >
              {isExpanded ? subItem.label : subItem.label.charAt(0)}
            </Link>
          ))}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}
