"use client";

import { Drawer, Group, MultiSelect, Stack, TextInput } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconSearch } from "@tabler/icons-react";
import { MemberFilterTrigger } from "./MemberFilters";

export interface SelectFilter {
  key: string;
  label: string;
  data: { value: string; label: string }[];
  value: string[];
  onChange: (next: string[]) => void;
}

/**
 * Filters for a table inside the member detail pages, as a right-hand drawer.
 *
 * Same shape as the promo pages and the accounts list: a badged trigger in the
 * table header, controls off-page, applied live with no Apply step. Filtering
 * itself is client-side — these datasets arrive whole with the page.
 */
export function TableFilterDrawer({
  title,
  search,
  onSearchChange,
  searchLabel = "Search",
  searchDescription,
  filters = [],
}: {
  title: string;
  search: string;
  onSearchChange: (next: string) => void;
  searchLabel?: string;
  searchDescription?: string;
  filters?: SelectFilter[];
}) {
  const [opened, drawer] = useDisclosure(false);
  const activeCount =
    (search ? 1 : 0) +
    filters.reduce((count, filter) => count + (filter.value.length ? 1 : 0), 0);

  return (
    <>
      <MemberFilterTrigger activeCount={activeCount} onClick={drawer.open} />
      <Drawer
        opened={opened}
        onClose={drawer.close}
        position="right"
        size={360}
        title={title}
      >
        <Stack gap="lg">
          <TextInput
            label={searchLabel}
            description={searchDescription}
            leftSection={<IconSearch size={15} />}
            value={search}
            onChange={(event) => onSearchChange(event.currentTarget.value)}
          />
          {filters.map((filter) => (
            <MultiSelect
              key={filter.key}
              label={filter.label}
              data={filter.data}
              value={filter.value}
              onChange={filter.onChange}
              searchable
              clearable
            />
          ))}
          <Group justify="flex-end">
            <MultiSelectSpacer />
          </Group>
        </Stack>
      </Drawer>
    </>
  );
}

// Keeps the drawer body from collapsing tight against the last control.
const MultiSelectSpacer = () => <div style={{ height: 4 }} />;
