import Filters from '@/components/Filters'
import { Checkbox } from '@blueprintjs/core'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTags } from '@inject/graphql/queries'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { useMemo } from 'react'
import type { Filter } from '../utils'

const Tags: FC<Filter<string[]>> = ({ selected, setSelected }) => {
  const onItemSelect = (tag: string) => setSelected(prev => [...prev, tag])
  const onRemove = (tagToRemove: string) =>
    setSelected(prev => prev.filter(tag => tag !== tagToRemove))

  const [{ data }] = useTypedQuery({
    query: GetTags,
    requestPolicy: 'network-only',
  })
  const allTags = useMemo(
    () => data?.tags?.filter(notEmpty).map(tag => tag?.name) || [],
    [data?.tags]
  )

  const filters = (
    <>
      {allTags.map(tag => (
        <Checkbox
          key={tag}
          label={tag}
          checked={selected.includes(tag)}
          onChange={() =>
            selected.includes(tag) ? onRemove(tag) : onItemSelect(tag)
          }
        />
      ))}
    </>
  )

  return (
    <Filters
      noWrap
      fill
      heading='Tags'
      content={filters}
      position='left'
      disabled={allTags.length === 0}
      title={allTags.length === 0 ? 'No tags available' : undefined}
      onSelectAll={() => setSelected(allTags)}
      onDeselectAll={() => setSelected([])}
    />
  )
}

export default Tags
