import Filters from '@/components/Filters'
import { Checkbox } from '@blueprintjs/core'
import { useGetTags } from '@inject/graphql/queries/GetTags.generated'
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 } = useGetTags({
    fetchPolicy: '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
