import { Box, TableToolbar } from '@wix/design-system';
import React from 'react';
import { classes, st } from './SearchOrCustomFilter.st.css.js';
import { ToolbarBaseProps } from '../ToolbarCollection';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { observer } from 'mobx-react-lite';
import { useIsMobile } from '../../hooks/useIsMobile';

export interface SearchOrCustomFilterProps {
  search: ToolbarBaseProps['search'];
}

function _SearchOrCustomFilter(props: SearchOrCustomFilterProps) {
  const { search } = props;

  const {
    toolbar: { responsive },
  } = useToolbarCollectionContext();
  const {
    _nextToShrink,
    search: searchResponsive,
    responsiveDisabled,
  } = responsive;

  const isMobile = useIsMobile();

  if (responsiveDisabled || isMobile) {
    return (
      <TableToolbar.Item
        className={st(isMobile ? classes.searchMobile : classes.search)}
      >
        {search}
      </TableToolbar.Item>
    );
  }

  const shouldShrink =
    _nextToShrink._count >= searchResponsive._count &&
    searchResponsive._shouldShrink;

  return (
    <Box
      direction="horizontal"
      maxWidth="240px"
      minWidth={shouldShrink ? '139px' : '140px'}
    >
      <Box width={shouldShrink ? '140px' : '240px'}>{search}</Box>
    </Box>
  );
}

export const SearchOrCustomFilter = observer(_SearchOrCustomFilter);
