import { Button, ButtonGroup } from '@blueprintjs/core'
import type { User } from '@inject/graphql/fragments/User.generated'
import type { AuthGroup } from '@inject/graphql/types'
import type { Dispatch, SetStateAction } from 'react'
import useUserTable from '../UserTable/useUserTable'

interface useUserTableSelectionProps {
  onAdd: (ids: string[]) => void
  groups: AuthGroup[]
  selectedUsers: string[]
  onCancel: () => void
  setSelectedUsers: Dispatch<SetStateAction<string[]>>
}

const useUserTableSelection = ({
  groups,
  onCancel,
  onAdd,
  selectedUsers,
  setSelectedUsers,
}: useUserTableSelectionProps) => {
  const { table } = useUserTable({
    onClick: (id: string) => {
      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([]),
  })

  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
