import type { MaybeElement, PopoverPosition } from '@blueprintjs/core'
import {
  Button,
  ButtonGroup,
  Classes,
  Divider,
  Popover,
} from '@blueprintjs/core'
import type { BlueprintIcons_16Id } from '@blueprintjs/icons/lib/esm/generated/16px/blueprint-icons-16'
import { css } from '@emotion/css'
import type { FC, ReactElement } from 'react'
import { useState } from 'react'

const sticky = css`
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: white;
  padding: 0.25rem;

  .${Classes.DARK} & {
    background-color: #2f343c;
  }
`

const contentWrapper = css`
  min-width: 18rem;
  max-height: 20rem;
  padding: 0 0.5rem;
  overflow-y: auto;
`

interface FiltersProps {
  heading?: string
  noWrap?: boolean
  title?: string
  content: string | ReactElement | undefined
  position: PopoverPosition
  onSelectAll: () => void
  onDeselectAll: () => void
  fill?: boolean
  disabled?: boolean
  icon?: BlueprintIcons_16Id | MaybeElement
}

const Filters: FC<FiltersProps> = ({
  title,
  noWrap,
  heading = 'Filters',
  content,
  position,
  onSelectAll,
  onDeselectAll,
  fill,
  disabled,
  icon,
}) => {
  const [open, setOpen] = useState(false)

  return (
    <Popover
      fill={fill}
      minimal
      position={position}
      content={
        <div>
          <div className={sticky}>
            <ButtonGroup minimal>
              <Button onClick={onSelectAll}>Select all</Button>
              <Divider />
              <Button onClick={onDeselectAll}>Deselect all</Button>
            </ButtonGroup>

            <Divider />
          </div>

          <div className={contentWrapper}>{content}</div>
        </div>
      }
      isOpen={open}
      onClose={() => setOpen(false)}
    >
      <Button
        title={title}
        style={{ whiteSpace: noWrap ? 'nowrap' : undefined }}
        active={open}
        icon={icon || 'filter'}
        disabled={disabled}
        alignText='left'
        fill={fill}
        minimal
        onClick={() => setOpen(true)}
      >
        {heading}
      </Button>
    </Popover>
  )
}

export default Filters
