import React, { ReactNode, ReactElement, MouseEvent } from 'react';

import Dropdown from '../Dropdown';
import Button from '../Button';

import { StyledFilterWrapper, StyledFilterTargetWrapper } from './StyledTable';

interface TableFilterProps {
  'data-test-id'?: string;
  hasFilterInput: boolean;
  renderFilter: (props: { onClose: () => void }) => ReactNode;
}

const TableFilter = ({
  renderFilter,
  hasFilterInput,
  'data-test-id': dataTestId,
}: TableFilterProps): ReactElement => {
  const [open, setOpen] = React.useState<boolean>(false);
  const onClose = React.useCallback(() => setOpen(false), [setOpen]);
  const onOpen = React.useCallback(() => setOpen(true), [setOpen]);
  const target = (
    <StyledFilterTargetWrapper>
      <Button.Icon
        intent={
          open === true || hasFilterInput === true ? 'primary' : 'subdued-text'
        }
        icon="funnel-filter"
        size="small"
        onClick={open === true ? onClose : onOpen}
        data-test-id={`${dataTestId}__filter`}
      />
    </StyledFilterTargetWrapper>
  );
  const content = renderFilter({ onClose });
  return (
    <StyledFilterWrapper
      onClick={(e: MouseEvent): void => {
        e.stopPropagation();
      }}
    >
      <Dropdown
        open={open}
        content={content}
        placement="bottom-right"
        target={target}
        onClose={onClose}
      />
    </StyledFilterWrapper>
  );
};

export default TableFilter;
