"use client";

import { ChevronUpIcon } from "@/assets/icons";
import { cn } from "@/lib/utils";
import { type ReactNode, useState } from "react";

interface CollapsibleFilterSectionProps {
  title: string;
  subtitle?: string;
  badge?: string;
  defaultOpen?: boolean;
  children: ReactNode;
}

/**
 * Nested accordion block for long filter forms (e.g. tender advanced fields).
 * Uses CSS grid height — independent from the main InlineListFiltersPanel GSAP shell.
 */
export default function CollapsibleFilterSection({
  title,
  subtitle,
  badge,
  defaultOpen,
  children,
}: CollapsibleFilterSectionProps) {
  const [open, setOpen] = useState(Boolean(defaultOpen));

  return (
    <div
      className={cn(
        "rounded-2xl border border-stroke/50 bg-white/50 backdrop-blur-md dark:border-white/[0.08] dark:bg-dark-2/45",
        open ? "overflow-visible" : "overflow-hidden",
        open && "ring-1 ring-primary/15 dark:ring-primary/25",
      )}
    >
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex w-full items-center justify-between gap-3 px-4 py-3.5 text-start transition hover:bg-white/60 dark:hover:bg-white/[0.04]"
      >
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-2">
            <span className="text-sm font-semibold text-dark dark:text-white">{title}</span>
            {badge ? (
              <span className="rounded-full bg-gradient-to-r from-primary/90 to-violet-500/85 px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-white">
                {badge}
              </span>
            ) : null}
          </div>
          {subtitle ? (
            <p className="mt-0.5 text-xs text-dark-5 dark:text-dark-6">{subtitle}</p>
          ) : null}
        </div>
        <ChevronUpIcon
          className={cn(
            "h-5 w-5 shrink-0 text-primary transition-transform duration-300 dark:text-primary/90",
            !open && "rotate-180",
          )}
        />
      </button>
      <div
        className={cn(
          "grid transition-[grid-template-rows] duration-300 ease-out",
          open ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
        )}
      >
        <div className={cn("min-h-0", open ? "overflow-visible" : "overflow-hidden")}>
          <div className="border-t border-stroke/40 px-4 pb-5 pt-1 dark:border-white/[0.06]">
            {children}
          </div>
        </div>
      </div>
    </div>
  );
}
