"use client";

import { useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { useAnchoredOverlay } from "~/hooks/useAnchoredOverlay.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";

export function FilterDropdown({
  label,
  children,
  widthClassName = "w-80",
  buttonClassName = "min-w-56",
  tooltipContent,
}: {
  label: string;
  children: ReactNode;
  widthClassName?: string;
  buttonClassName?: string;
  tooltipContent?: ReactNode;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const { triggerRef, panelRef, position, handleOpenChange } = useAnchoredOverlay<HTMLDivElement>({
    open: isOpen,
    onClose: () => setIsOpen(false),
    matchTriggerWidth: true,
  });

  return (
    <div ref={triggerRef} className="relative">
      <div className="flex items-center gap-2">
        <button
          type="button"
          onClick={() => {
            const nextOpen = !isOpen;
            handleOpenChange(nextOpen);
            setIsOpen(nextOpen);
          }}
          className={`inline-flex items-center justify-between gap-3 rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-700 shadow-sm transition hover:border-gray-400 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800 ${buttonClassName}`}
        >
          <span className="text-left">{label}</span>
          <span className="text-xs text-gray-400 dark:text-gray-500">{isOpen ? "▲" : "▼"}</span>
        </button>
        {tooltipContent ? <InfoTooltip content={tooltipContent} width="w-72" /> : null}
      </div>
      {isOpen &&
        createPortal(
          <div
            ref={panelRef}
            style={{
              position: "fixed",
              top: position.top,
              left: position.left,
              minWidth: position.minWidth,
            }}
            className={`z-[9998] rounded-2xl border border-gray-200 bg-white p-3 shadow-xl dark:border-gray-700 dark:bg-gray-900 ${widthClassName}`}
          >
            {children}
          </div>,
          document.body,
        )}
    </div>
  );
}
