import { Button, ButtonGroup } from '@blueprintjs/core'
import type { User } from '@inject/graphql/fragment-types'
import type { Dispatch, SetStateAction } from 'react'
import useUserTable from '../UserTable/useUserTable'
import type { AUTH_GROUPS } from '../UserTable/utils'

interface useUserTableSelectionProps {
  onAdd: (ids: string[]) => void
  groups: typeof AUTH_GROUPS
  selectedUsers: string[]
  onCancel: () => void
  setSelectedUsers: Dispatch<SetStateAction<string[]>>
  filterPredicate?: (user: User) => boolean
}

const useUserTableSelection = ({
  groups,
  onCancel,
  onAdd,
  selectedUsers,
  setSelectedUsers,
  filterPredicate,
}: useUserTableSelectionProps) => {
  const { table } = useUserTable({
    onClick: (id: string) => {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      selectedUsers.includes(id)
        ? setSelectedUsers(prev => {
            const i = selectedUsers.indexOf(id)
            return [...prev.slice(0, i), ...prev.slice(i + 1)]
          })
        : setSelectedUsers(prev => [...prev, id])
    },
    selectedUsers,
    active: { active: true, inactive: false },
    groups,
    properties: [
      {
        id: 'id',
        name: 'Username',
        getValue: (user: User) => user.username,
      },
      {
        id: 'firstName',
        name: 'First name',
        getValue: (user: User) => user.firstName,
      },
      {
        id: 'lastName',
        name: 'Last name',
        getValue: (user: User) => user.lastName,
      },
      {
        id: 'group',
        name: 'Group',
        getValue: (user: User) => user.group,
      },
      {
        id: 'tags',
        name: 'Tags',
        getValue: (user: User) =>
          (user.tags || []).map(tag => tag.name).join(', '),
      },
    ],
    onSelectAll: (allIds: string[]) => setSelectedUsers(allIds),
    onDeselectAll: () => setSelectedUsers([]),
    filterPredicate,
  })

  return {
    buttons: (
      <ButtonGroup>
        <Button onClick={onCancel} text='Cancel' />
        <Button
          disabled={selectedUsers.length === 0}
          title={selectedUsers.length === 0 ? 'No users selected' : ''}
          intent='primary'
          onClick={() => {
            onAdd(selectedUsers)
            // TODO: only reset if successful
            setSelectedUsers([])
          }}
          text={`Add (${selectedUsers.length})`}
        />
      </ButtonGroup>
    ),
    table,
  }
}

export default useUserTableSelection
