aboutsummaryrefslogtreecommitdiff
path: root/src/components/input/LookupField.tsx
blob: c1d419f743640a7334fcb19e917ca355e213edf0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { ComboBox, type ComboBoxProps, ListItem, Loading, useDebounce } from '@umami/react-zen';
import { endOfDay, subMonths } from 'date-fns';
import { type SetStateAction, useMemo, useState } from 'react';
import { Empty } from '@/components/common/Empty';
import { useMessages, useWebsiteValuesQuery } from '@/components/hooks';

export interface LookupFieldProps extends ComboBoxProps {
  websiteId: string;
  type: string;
  value: string;
  onChange: (value: string) => void;
}

export function LookupField({ websiteId, type, value, onChange, ...props }: LookupFieldProps) {
  const { formatMessage, messages } = useMessages();
  const [search, setSearch] = useState(value);
  const searchValue = useDebounce(search, 300);
  const startDate = subMonths(endOfDay(new Date()), 6);
  const endDate = endOfDay(new Date());

  const { data, isLoading } = useWebsiteValuesQuery({
    websiteId,
    type,
    search: searchValue,
    startDate,
    endDate,
  });

  const items: string[] = useMemo(() => {
    return data?.map(({ value }) => value) || [];
  }, [data]);

  const handleSearch = (value: SetStateAction<string>) => {
    setSearch(value);
  };

  return (
    <ComboBox
      aria-label="LookupField"
      {...props}
      items={items}
      inputValue={value}
      onInputChange={value => {
        handleSearch(value);
        onChange?.(value);
      }}
      formValue="text"
      allowsEmptyCollection
      allowsCustomValue
      renderEmptyState={() =>
        isLoading ? (
          <Loading placement="center" icon="dots" />
        ) : (
          <Empty message={formatMessage(messages.noResultsFound)} />
        )
      }
    >
      {items.map(item => (
        <ListItem key={item} id={item}>
          {item}
        </ListItem>
      ))}
    </ComboBox>
  );
}