import { ChevronDown, X } from 'lucide-react'
import clsx from 'clsx'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'

interface FilterPillProps {
  /** Category label, always shown ("Date", "Type", etc.). */
  label: string
  /** Currently unused in the rendered output — the inline value display
   *  was making active pills wider than inactive ones. Kept on the
   *  interface so callers don't have to change. The value is still
   *  surfaced via the title attribute for hover discovery. */
  value?: string | null
  isActive?: boolean
  /** When provided + isActive, an X appears inside the pill that clears
   *  this filter without opening the popover. */
  onClear?: () => void
  /** Popover contents — usually the existing control for this filter. */
  children: React.ReactNode
  /** Force the popover open programmatically (rare). */
  defaultOpen?: boolean
  /** Override the PopoverContent className — use when the child has its
   *  own padding (e.g. MultiSelect rows) and the default `p-3` doubles
   *  up. */
  contentClassName?: string
}

/**
 * Toolbar pill that hosts a filter category. Click the pill to open a
 * small popover with the actual control; the popover closes on outside
 * click or Escape. Built on Radix Popover so positioning, focus
 * management, portal rendering, and dismissal come for free — the
 * pill only owns the trigger styling and the "clear" affordance.
 */
export function FilterPill({
  label,
  value,
  isActive = false,
  onClear,
  children,
  defaultOpen = false,
  contentClassName,
}: FilterPillProps) {
  return (
    <Popover defaultOpen={defaultOpen}>
      <PopoverTrigger asChild>
        <button
          title={isActive && value ? `${label}: ${value}` : label}
          className={clsx(
            // Fixed height + py-0 so neither the X clear icon nor the
            // chevron can stretch the pill vertically when the active
            // state swaps them in.
            'flex h-7 items-center gap-1 rounded-full border px-2.5 py-0 text-xs transition-colors',
            isActive
              ? 'border-primary/40 bg-primary/15 text-primary'
              : 'border-border bg-surface-2 text-text-muted hover:bg-surface-offset hover:text-text'
          )}
        >
          <span className={clsx(isActive && 'font-medium')}>{label}</span>
          {isActive && onClear ? (
            <span
              role="button"
              tabIndex={0}
              onClick={(e) => {
                e.stopPropagation()
                onClear()
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault()
                  e.stopPropagation()
                  onClear()
                }
              }}
              className="ml-0.5 inline-flex h-3.5 w-4 cursor-pointer items-center justify-center rounded-full hover:bg-primary/30"
              title={`Clear ${label}`}
              aria-label={`Clear ${label}`}
            >
              <X className="h-3 w-3" />
            </span>
          ) : (
            <span className="inline-flex h-3.5 w-4 items-center justify-center">
              <ChevronDown className="h-3 w-3 opacity-60" />
            </span>
          )}
        </button>
      </PopoverTrigger>
      <PopoverContent
        align="start"
        className={clsx('w-auto', contentClassName ?? 'p-2')}
      >
        {children}
      </PopoverContent>
    </Popover>
  )
}
