import React, {
  ChangeEventHandler,
  MouseEventHandler,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import {
  Box,
  Chip,
  Text,
  Icon,
  Icons,
  Line,
  config,
  PopOut,
  Menu,
  MenuItem,
  Header,
  toRem,
  Scroll,
  Button,
  Input,
  Badge,
  RectCords,
  IconSrc,
} from 'folds';
import { SearchOrderBy } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { getMxIdLocalPart } from '../../utils/matrix';
import { getRoomIconSrc } from '../../utils/room';
import { factoryRoomIdByAtoZ } from '../../utils/sort';
import {
  SearchItemStrGetter,
  UseAsyncSearchOptions,
  useAsyncSearch,
} from '../../hooks/useAsyncSearch';
import { DebounceOptions, useDebounce } from '../../hooks/useDebounce';
import { VirtualTile } from '../../components/virtualizer';
import { stopPropagation } from '../../utils/keyboard';
import { MsgTypeFilter } from './useMessageSearch';

const MSG_TYPE_FILTER_OPTIONS: { msgType: MsgTypeFilter; label: string; icon: IconSrc }[] = [
  { msgType: 'm.image', label: 'Images', icon: Icons.Photo },
  { msgType: 'm.file', label: 'Files', icon: Icons.File },
  { msgType: 'm.video', label: 'Video', icon: Icons.VideoCamera },
];

type OrderButtonProps = {
  order?: string;
  onChange: (order?: string) => void;
};
function OrderButton({ order, onChange }: OrderButtonProps) {
  const [menuAnchor, setMenuAnchor] = useState<RectCords>();
  const rankOrder = order === SearchOrderBy.Rank;

  const setOrder = (o?: string) => {
    setMenuAnchor(undefined);
    onChange(o);
  };
  const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
    setMenuAnchor(evt.currentTarget.getBoundingClientRect());
  };

  return (
    <PopOut
      anchor={menuAnchor}
      align="End"
      position="Bottom"
      content={
        <FocusTrap
          focusTrapOptions={{
            initialFocus: false,
            onDeactivate: () => setMenuAnchor(undefined),
            clickOutsideDeactivates: true,
            escapeDeactivates: stopPropagation,
          }}
        >
          <Menu variant="Surface">
            <Header size="300" variant="Surface" style={{ padding: `0 ${config.space.S300}` }}>
              <Text size="L400">Sort by</Text>
            </Header>
            <Line variant="Surface" size="300" />
            <div style={{ padding: config.space.S100 }}>
              <MenuItem
                onClick={() => setOrder()}
                variant="Surface"
                size="300"
                radii="300"
                aria-pressed={!rankOrder}
              >
                <Text size="T300">Recent</Text>
              </MenuItem>
              <MenuItem
                onClick={() => setOrder(SearchOrderBy.Rank)}
                variant="Surface"
                size="300"
                radii="300"
                aria-pressed={rankOrder}
              >
                <Text size="T300">Relevance</Text>
              </MenuItem>
            </div>
          </Menu>
        </FocusTrap>
      }
    >
      <Chip
        variant="SurfaceVariant"
        radii="Pill"
        after={<Icon size="50" src={Icons.Sort} />}
        onClick={handleOpenMenu}
      >
        {rankOrder ? <Text size="T200">Relevance</Text> : <Text size="T200">Recent</Text>}
      </Chip>
    </PopOut>
  );
}

const SEARCH_OPTS: UseAsyncSearchOptions = {
  limit: 20,
  matchOptions: {
    contain: true,
  },
};
const SEARCH_DEBOUNCE_OPTS: DebounceOptions = {
  wait: 200,
};

type SelectRoomButtonProps = {
  roomList: string[];
  selectedRooms?: string[];
  onChange: (rooms?: string[]) => void;
};
function SelectRoomButton({ roomList, selectedRooms, onChange }: SelectRoomButtonProps) {
  const mx = useMatrixClient();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [menuAnchor, setMenuAnchor] = useState<RectCords>();
  const [localSelected, setLocalSelected] = useState(selectedRooms);

  const getRoomNameStr: SearchItemStrGetter<string> = useCallback(
    (rId) => mx.getRoom(rId)?.name ?? rId,
    [mx],
  );

  const [searchResult, _searchRoom, resetSearch] = useAsyncSearch(
    roomList,
    getRoomNameStr,
    SEARCH_OPTS,
  );
  const rooms = useMemo(
    () => Array.from(searchResult?.items ?? roomList).sort(factoryRoomIdByAtoZ(mx)),
    [searchResult, roomList, mx],
  );

  const virtualizer = useVirtualizer({
    count: rooms.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 32,
    overscan: 5,
  });
  const vItems = virtualizer.getVirtualItems();

  const searchRoom = useDebounce(_searchRoom, SEARCH_DEBOUNCE_OPTS);
  const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
    const value = evt.currentTarget.value.trim();
    if (!value) {
      resetSearch();
      return;
    }
    searchRoom(value);
  };

  const handleRoomClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
    const roomId = evt.currentTarget.getAttribute('data-room-id');
    if (!roomId) return;
    if (localSelected?.includes(roomId)) {
      setLocalSelected(localSelected?.filter((rId) => rId !== roomId));
      return;
    }
    const addedRooms = [...(localSelected ?? [])];
    addedRooms.push(roomId);
    setLocalSelected(addedRooms);
  };

  const handleSave = () => {
    setMenuAnchor(undefined);
    onChange(localSelected);
  };

  const handleDeselectAll = () => {
    setMenuAnchor(undefined);
    onChange(undefined);
  };

  useEffect(() => {
    setLocalSelected(selectedRooms);
    resetSearch();
  }, [menuAnchor, selectedRooms, resetSearch]);

  const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
    setMenuAnchor(evt.currentTarget.getBoundingClientRect());
  };

  return (
    <PopOut
      anchor={menuAnchor}
      align="Center"
      position="Bottom"
      content={
        <FocusTrap
          focusTrapOptions={{
            initialFocus: false,
            onDeactivate: () => setMenuAnchor(undefined),
            clickOutsideDeactivates: true,
            escapeDeactivates: stopPropagation,
          }}
        >
          <Menu variant="Surface" style={{ width: toRem(250) }}>
            <Box direction="Column" style={{ maxHeight: toRem(450), maxWidth: toRem(300) }}>
              <Box
                shrink="No"
                direction="Column"
                gap="100"
                style={{ padding: config.space.S200, paddingBottom: 0 }}
              >
                <Text size="L400">Search</Text>
                <Input
                  onChange={handleSearchChange}
                  size="300"
                  radii="300"
                  after={
                    searchResult && searchResult.items.length > 0 ? (
                      <Badge variant="Secondary" size="400" radii="Pill">
                        <Text size="L400">{searchResult.items.length}</Text>
                      </Badge>
                    ) : null
                  }
                />
              </Box>
              <Scroll ref={scrollRef} size="300" hideTrack>
                <Box
                  direction="Column"
                  gap="100"
                  style={{
                    padding: config.space.S200,
                    paddingRight: 0,
                  }}
                >
                  {!searchResult && <Text size="L400">Rooms</Text>}
                  {searchResult && <Text size="L400">{`Rooms for "${searchResult.query}"`}</Text>}
                  {searchResult && searchResult.items.length === 0 && (
                    <Text style={{ padding: config.space.S400 }} size="T300" align="Center">
                      No match found!
                    </Text>
                  )}
                  <div
                    style={{
                      position: 'relative',
                      height: virtualizer.getTotalSize(),
                    }}
                  >
                    {vItems.map((vItem) => {
                      const roomId = rooms[vItem.index];
                      const room = mx.getRoom(roomId);
                      if (!room) return null;
                      const selected = localSelected?.includes(roomId);

                      return (
                        <VirtualTile
                          virtualItem={vItem}
                          style={{ paddingBottom: config.space.S100 }}
                          ref={virtualizer.measureElement}
                          key={vItem.index}
                        >
                          <MenuItem
                            data-room-id={roomId}
                            onClick={handleRoomClick}
                            variant={selected ? 'Success' : 'Surface'}
                            size="300"
                            radii="300"
                            aria-pressed={selected}
                            before={
                              <Icon
                                size="50"
                                src={getRoomIconSrc(Icons, room.getType(), room.getJoinRule())}
                              />
                            }
                          >
                            <Text truncate size="T300">
                              {room.name}
                            </Text>
                          </MenuItem>
                        </VirtualTile>
                      );
                    })}
                  </div>
                </Box>
              </Scroll>
              <Line variant="Surface" size="300" />
              <Box shrink="No" direction="Column" gap="100" style={{ padding: config.space.S200 }}>
                <Button size="300" variant="Secondary" radii="300" onClick={handleSave}>
                  {localSelected && localSelected.length > 0 ? (
                    <Text size="B300">Save ({localSelected.length})</Text>
                  ) : (
                    <Text size="B300">Save</Text>
                  )}
                </Button>
                <Button
                  size="300"
                  radii="300"
                  variant="Secondary"
                  fill="Soft"
                  onClick={handleDeselectAll}
                  disabled={!localSelected || localSelected.length === 0}
                >
                  <Text size="B300">Deselect All</Text>
                </Button>
              </Box>
            </Box>
          </Menu>
        </FocusTrap>
      }
    >
      <Chip
        onClick={handleOpenMenu}
        variant="SurfaceVariant"
        radii="Pill"
        before={<Icon size="100" src={Icons.PlusCircle} />}
      >
        <Text size="T200">Select Rooms</Text>
      </Chip>
    </PopOut>
  );
}

type SelectSenderButtonProps = {
  selectedSenders?: string[];
  onChange: (senders?: string[]) => void;
};
function SelectSenderButton({ selectedSenders, onChange }: SelectSenderButtonProps) {
  const mx = useMatrixClient();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [menuAnchor, setMenuAnchor] = useState<RectCords>();
  const [localSelected, setLocalSelected] = useState(selectedSenders);

  const knownUsers = useMemo(() => {
    const ids = new Set<string>();
    mx.getRooms().forEach((room) => {
      room.getJoinedMembers().forEach((m) => {
        if (m.userId !== mx.getSafeUserId()) ids.add(m.userId);
      });
    });
    return Array.from(ids).sort();
  }, [mx]);

  const getUserDisplayStr: SearchItemStrGetter<string> = useCallback(
    (userId) => {
      const user = mx.getUser(userId);
      return user?.displayName ?? getMxIdLocalPart(userId) ?? userId;
    },
    [mx],
  );

  const [searchResult, _searchUser, resetSearch] = useAsyncSearch(
    knownUsers,
    getUserDisplayStr,
    SEARCH_OPTS,
  );
  const users = searchResult?.items ?? knownUsers;

  const virtualizer = useVirtualizer({
    count: users.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 32,
    overscan: 5,
  });
  const vItems = virtualizer.getVirtualItems();

  const searchUser = useDebounce(_searchUser, SEARCH_DEBOUNCE_OPTS);
  const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
    const value = evt.currentTarget.value.trim();
    if (!value) {
      resetSearch();
      return;
    }
    searchUser(value);
  };

  const handleUserClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
    const userId = evt.currentTarget.getAttribute('data-user-id');
    if (!userId) return;
    if (localSelected?.includes(userId)) {
      setLocalSelected(localSelected.filter((id) => id !== userId));
      return;
    }
    setLocalSelected([...(localSelected ?? []), userId]);
  };

  const handleSave = () => {
    setMenuAnchor(undefined);
    onChange(localSelected && localSelected.length > 0 ? localSelected : undefined);
  };

  const handleDeselectAll = () => {
    setMenuAnchor(undefined);
    onChange(undefined);
  };

  useEffect(() => {
    setLocalSelected(selectedSenders);
    resetSearch();
  }, [menuAnchor, selectedSenders, resetSearch]);

  return (
    <PopOut
      anchor={menuAnchor}
      align="Center"
      position="Bottom"
      content={
        <FocusTrap
          focusTrapOptions={{
            initialFocus: false,
            onDeactivate: () => setMenuAnchor(undefined),
            clickOutsideDeactivates: true,
            escapeDeactivates: stopPropagation,
          }}
        >
          <Menu variant="Surface" style={{ width: toRem(250) }}>
            <Box direction="Column" style={{ maxHeight: toRem(400), maxWidth: toRem(300) }}>
              <Box
                shrink="No"
                direction="Column"
                gap="100"
                style={{ padding: config.space.S200, paddingBottom: 0 }}
              >
                <Text size="L400">From</Text>
                <Input
                  onChange={handleSearchChange}
                  size="300"
                  radii="300"
                  placeholder="Search people..."
                />
              </Box>
              <Scroll ref={scrollRef} size="300" hideTrack>
                <Box
                  direction="Column"
                  gap="100"
                  style={{ padding: config.space.S200, paddingRight: 0 }}
                >
                  {users.length === 0 && (
                    <Text style={{ padding: config.space.S400 }} size="T300" align="Center">
                      No match found!
                    </Text>
                  )}
                  <div style={{ position: 'relative', height: virtualizer.getTotalSize() }}>
                    {vItems.map((vItem) => {
                      const userId = users[vItem.index];
                      const user = mx.getUser(userId);
                      const name = user?.displayName ?? getMxIdLocalPart(userId) ?? userId;
                      const selected = localSelected?.includes(userId);
                      return (
                        <VirtualTile
                          virtualItem={vItem}
                          style={{ paddingBottom: config.space.S100 }}
                          ref={virtualizer.measureElement}
                          key={vItem.index}
                        >
                          <MenuItem
                            data-user-id={userId}
                            onClick={handleUserClick}
                            variant={selected ? 'Success' : 'Surface'}
                            size="300"
                            radii="300"
                            aria-pressed={selected}
                            before={<Icon size="50" src={Icons.User} />}
                          >
                            <Text truncate size="T300">
                              {name}
                            </Text>
                          </MenuItem>
                        </VirtualTile>
                      );
                    })}
                  </div>
                </Box>
              </Scroll>
              <Line variant="Surface" size="300" />
              <Box shrink="No" direction="Column" gap="100" style={{ padding: config.space.S200 }}>
                <Button size="300" variant="Secondary" radii="300" onClick={handleSave}>
                  {localSelected && localSelected.length > 0 ? (
                    <Text size="B300">Save ({localSelected.length})</Text>
                  ) : (
                    <Text size="B300">Save</Text>
                  )}
                </Button>
                <Button
                  size="300"
                  radii="300"
                  variant="Secondary"
                  fill="Soft"
                  onClick={handleDeselectAll}
                  disabled={!localSelected || localSelected.length === 0}
                >
                  <Text size="B300">Deselect All</Text>
                </Button>
              </Box>
            </Box>
          </Menu>
        </FocusTrap>
      }
    >
      <Chip
        onClick={(e: React.MouseEvent<HTMLButtonElement>) =>
          setMenuAnchor(e.currentTarget.getBoundingClientRect())
        }
        variant="SurfaceVariant"
        radii="Pill"
        before={<Icon size="100" src={Icons.User} />}
      >
        <Text size="T200">From</Text>
      </Chip>
    </PopOut>
  );
}

type DateRangeButtonProps = {
  fromTs?: number;
  toTs?: number;
  onChange: (fromTs?: number, toTs?: number) => void;
};
function DateRangeButton({ fromTs, toTs, onChange }: DateRangeButtonProps) {
  const [menuAnchor, setMenuAnchor] = useState<RectCords>();
  const toISODate = (ts: number) => new Date(ts).toISOString().split('T')[0];
  const fromDate = fromTs ? toISODate(fromTs) : '';
  const toDate = toTs ? toISODate(toTs) : '';

  const handleFrom = (val: string) => {
    onChange(val ? new Date(val).setHours(0, 0, 0, 0) : undefined, toTs);
  };
  const handleTo = (val: string) => {
    onChange(fromTs, val ? new Date(val).setHours(23, 59, 59, 999) : undefined);
  };

  const hasRange = !!fromTs || !!toTs;
  const label = hasRange
    ? [fromTs && toISODate(fromTs), toTs && toISODate(toTs)].filter(Boolean).join(' – ')
    : 'Date range';

  return (
    <PopOut
      anchor={menuAnchor}
      align="End"
      position="Bottom"
      content={
        <FocusTrap
          focusTrapOptions={{
            initialFocus: false,
            onDeactivate: () => setMenuAnchor(undefined),
            clickOutsideDeactivates: true,
          }}
        >
          <Menu variant="Surface" style={{ padding: config.space.S300, minWidth: toRem(220) }}>
            <Box direction="Column" gap="200">
              <Box direction="Column" gap="100">
                <Text size="L400">Quick pick</Text>
                <Box gap="100" wrap="Wrap">
                  {(
                    [
                      { label: 'Today', days: 0 },
                      { label: 'Last week', days: 7 },
                      { label: 'Last month', days: 30 },
                      { label: 'Last year', days: 365 },
                    ] as const
                  ).map(({ label: l, days }) => {
                    const now = Date.now();
                    const from =
                      days === 0
                        ? new Date().setHours(0, 0, 0, 0)
                        : now - days * 24 * 60 * 60 * 1000;
                    return (
                      <Chip
                        key={l}
                        radii="Pill"
                        variant="SurfaceVariant"
                        onClick={() => {
                          onChange(from, now);
                          setMenuAnchor(undefined);
                        }}
                      >
                        <Text size="T200">{l}</Text>
                      </Chip>
                    );
                  })}
                </Box>
              </Box>
              <Line variant="Surface" size="300" />
              <Box direction="Column" gap="100">
                <Text size="L400">From</Text>
                <Input
                  type="date"
                  variant="SurfaceVariant"
                  size="300"
                  radii="300"
                  value={fromDate}
                  max={toDate || undefined}
                  onChange={(e) => handleFrom(e.target.value)}
                />
              </Box>
              <Box direction="Column" gap="100">
                <Text size="L400">To</Text>
                <Input
                  type="date"
                  variant="SurfaceVariant"
                  size="300"
                  radii="300"
                  value={toDate}
                  min={fromDate || undefined}
                  onChange={(e) => handleTo(e.target.value)}
                />
              </Box>
              {hasRange && (
                <Button
                  size="300"
                  variant="Critical"
                  fill="None"
                  radii="300"
                  onClick={() => {
                    onChange(undefined, undefined);
                    setMenuAnchor(undefined);
                  }}
                >
                  <Text size="B300">Clear</Text>
                </Button>
              )}
            </Box>
          </Menu>
        </FocusTrap>
      }
    >
      <Chip
        variant={hasRange ? 'Primary' : 'SurfaceVariant'}
        radii="Pill"
        before={<Icon size="100" src={Icons.RecentClock} />}
        after={hasRange ? <Icon size="50" src={Icons.Cross} /> : undefined}
        onClick={(e: React.MouseEvent<HTMLButtonElement>) =>
          setMenuAnchor(e.currentTarget.getBoundingClientRect())
        }
      >
        <Text size="T200">{label}</Text>
      </Chip>
    </PopOut>
  );
}

type SearchFiltersProps = {
  defaultRoomsFilterName: string;
  allowGlobal?: boolean;
  roomList: string[];
  selectedRooms?: string[];
  onSelectedRoomsChange: (selectedRooms?: string[]) => void;
  global?: boolean;
  onGlobalChange: (global?: boolean) => void;
  order?: string;
  onOrderChange: (order?: string) => void;
  selectedSenders?: string[];
  onSelectedSendersChange: (senders?: string[]) => void;
  fromTs?: number;
  toTs?: number;
  onDateRangeChange: (fromTs?: number, toTs?: number) => void;
  containsUrl?: boolean;
  onContainsUrlChange: (value?: boolean) => void;
  msgTypeFilters: MsgTypeFilter[];
  onToggleMsgTypeFilter: (msgType: MsgTypeFilter) => void;
  pinnedOnly: boolean;
  onTogglePinnedOnly: () => void;
};
export function SearchFilters({
  defaultRoomsFilterName,
  allowGlobal,
  roomList,
  selectedRooms,
  onSelectedRoomsChange,
  global,
  order,
  onGlobalChange,
  onOrderChange,
  selectedSenders,
  onSelectedSendersChange,
  fromTs,
  toTs,
  onDateRangeChange,
  containsUrl,
  onContainsUrlChange,
  msgTypeFilters,
  onToggleMsgTypeFilter,
  pinnedOnly,
  onTogglePinnedOnly,
}: SearchFiltersProps) {
  const mx = useMatrixClient();

  return (
    <Box direction="Column" gap="100">
      <Text size="L400">Filter</Text>
      <Box gap="200" wrap="Wrap">
        <Chip
          variant={!global ? 'Success' : 'Surface'}
          aria-pressed={!global}
          before={!global && <Icon size="100" src={Icons.Check} />}
          outlined
          onClick={() => onGlobalChange()}
        >
          <Text size="T200">{defaultRoomsFilterName}</Text>
        </Chip>
        {allowGlobal && (
          <Chip
            variant={global ? 'Success' : 'Surface'}
            aria-pressed={global}
            before={global && <Icon size="100" src={Icons.Check} />}
            outlined
            onClick={() => onGlobalChange(true)}
          >
            <Text size="T200">Global</Text>
          </Chip>
        )}
        <Line
          style={{ margin: `${config.space.S100} 0` }}
          direction="Vertical"
          variant="Surface"
          size="300"
        />
        {selectedRooms?.map((roomId) => {
          const room = mx.getRoom(roomId);
          if (!room) return null;

          return (
            <Chip
              key={roomId}
              variant="Success"
              onClick={() => onSelectedRoomsChange(selectedRooms.filter((rId) => rId !== roomId))}
              radii="Pill"
              before={
                <Icon size="50" src={getRoomIconSrc(Icons, room.getType(), room.getJoinRule())} />
              }
              after={<Icon size="50" src={Icons.Cross} />}
            >
              <Text size="T200">{room.name}</Text>
            </Chip>
          );
        })}
        <SelectRoomButton
          roomList={roomList}
          selectedRooms={selectedRooms}
          onChange={onSelectedRoomsChange}
        />
        <Line
          style={{ margin: `${config.space.S100} 0` }}
          direction="Vertical"
          variant="Surface"
          size="300"
        />
        {selectedSenders?.map((userId) => {
          const user = mx.getUser(userId);
          const name = user?.displayName ?? getMxIdLocalPart(userId) ?? userId;
          return (
            <Chip
              key={userId}
              variant="Primary"
              radii="Pill"
              before={<Icon size="50" src={Icons.User} />}
              after={<Icon size="50" src={Icons.Cross} />}
              onClick={() => onSelectedSendersChange(selectedSenders.filter((id) => id !== userId))}
            >
              <Text size="T200">{name}</Text>
            </Chip>
          );
        })}
        <SelectSenderButton selectedSenders={selectedSenders} onChange={onSelectedSendersChange} />
        <Box grow="Yes" data-spacing-node />
        <Chip
          variant={containsUrl ? 'Success' : 'SurfaceVariant'}
          outlined={!!containsUrl}
          radii="Pill"
          aria-pressed={!!containsUrl}
          before={<Icon size="100" src={Icons.Link} />}
          after={containsUrl ? <Icon size="50" src={Icons.Cross} /> : undefined}
          onClick={() => onContainsUrlChange(containsUrl ? undefined : true)}
        >
          <Text size="T200">Has link</Text>
        </Chip>
        {MSG_TYPE_FILTER_OPTIONS.map(({ msgType, label, icon }) => {
          const active = msgTypeFilters.includes(msgType);
          return (
            <Chip
              key={msgType}
              variant={active ? 'Success' : 'SurfaceVariant'}
              outlined={active}
              radii="Pill"
              aria-pressed={active}
              before={<Icon size="100" src={icon} />}
              after={active ? <Icon size="50" src={Icons.Cross} /> : undefined}
              onClick={() => onToggleMsgTypeFilter(msgType)}
            >
              <Text size="T200">{label}</Text>
            </Chip>
          );
        })}
        <Chip
          variant={pinnedOnly ? 'Success' : 'SurfaceVariant'}
          outlined={pinnedOnly}
          radii="Pill"
          aria-pressed={pinnedOnly}
          before={<Icon size="100" src={Icons.Pin} />}
          after={pinnedOnly ? <Icon size="50" src={Icons.Cross} /> : undefined}
          onClick={onTogglePinnedOnly}
        >
          <Text size="T200">Pinned</Text>
        </Chip>
        <DateRangeButton fromTs={fromTs} toTs={toTs} onChange={onDateRangeChange} />
        <OrderButton order={order} onChange={onOrderChange} />
      </Box>
    </Box>
  );
}
