'use client';

import {HStack} from '@astryxdesign/core/Layout';
import {TextInput} from '@astryxdesign/core/TextInput';
import {
  SegmentedControl,
  SegmentedControlItem,
} from '@astryxdesign/core/SegmentedControl';
import {Text} from '@astryxdesign/core/Text';

export interface FilterOption {
  value: string;
  label: string;
  /** Shown after the label, e.g. a count. */
  hint?: string | number;
}

/**
 * Search plus a single-select filter, above a collection.
 *
 * Store, Lyts and Staff all present "a grid of things you can narrow down",
 * so the control strip is defined once. A SegmentedControl rather than a
 * dropdown because these sets are small and always visible — a merchant
 * scanning for the one closed store should not have to open a menu to
 * discover that "closed" is an option, or to see there are none.
 *
 * The result count is part of the bar rather than floating above the grid:
 * when a filter returns nothing, the count is the fastest explanation of why
 * the space below is empty.
 */
export function FilterBar({
  query,
  onQueryChange,
  placeholder = 'Search…',
  filterValue,
  onFilterChange,
  options,
  filterLabel,
  resultCount,
  resultNoun,
  actions,
}: {
  query: string;
  onQueryChange: (v: string) => void;
  placeholder?: string;
  filterValue: string;
  onFilterChange: (v: string) => void;
  options: FilterOption[];
  /** Accessible name for the filter group — never rendered visually. */
  filterLabel: string;
  resultCount?: number;
  resultNoun?: string;
  actions?: React.ReactNode;
}) {
  return (
    <HStack gap={3} vAlign="center" wrap="wrap" hAlign="between">
      <HStack gap={3} vAlign="center" wrap="wrap">
        <TextInput
          label={placeholder}
          isLabelHidden
          placeholder={placeholder}
          value={query}
          onChange={onQueryChange}
          startIcon="search"
          hasClear
          size="sm"
          width={260}
        />
        <SegmentedControl
          value={filterValue}
          onChange={onFilterChange}
          label={filterLabel}
          size="sm"
        >
          {options.map((o) => (
            <SegmentedControlItem
              key={o.value}
              value={o.value}
              label={
                o.hint !== undefined ? `${o.label} (${o.hint})` : o.label
              }
            />
          ))}
        </SegmentedControl>
      </HStack>

      <HStack gap={3} vAlign="center">
        {resultCount !== undefined ? (
          <Text size="sm" color="secondary">
            {resultCount} {resultNoun ?? 'results'}
          </Text>
        ) : null}
        {actions}
      </HStack>
    </HStack>
  );
}
