import {
  maybeSortingFunction,
  stringSortingFunction,
} from '@/components/Table/utils'
import Tags from '@/components/Tags'
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 {
  groups: typeof AUTH_GROUPS
  selectedUsers: string[]
  setSelectedUsers: Dispatch<SetStateAction<string[]>>
  filterPredicate?: (user: User) => boolean
}

const useUserTableSelection = ({
  groups,
  selectedUsers,
  setSelectedUsers,
  filterPredicate,
}: useUserTableSelectionProps) => {
  const tableProps = 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,
    columns: [
      {
        id: 'username',
        name: 'Username',
        display: true,
        renderValue: (user: User) => user.username,
        sortingFunction: (a, b) =>
          stringSortingFunction(a.username, b.username),
      },
      {
        id: 'firstName',
        name: 'First name',
        display: true,
        renderValue: (user: User) => user.firstName,
        sortingFunction: (a, b) =>
          maybeSortingFunction(a.firstName, b.firstName, stringSortingFunction),
      },
      {
        id: 'lastName',
        name: 'Last name',
        display: true,
        renderValue: (user: User) => user.lastName,
        sortingFunction: (a, b) =>
          maybeSortingFunction(a.lastName, b.lastName, stringSortingFunction),
      },
      {
        id: 'group',
        name: 'Group',
        display: true,
        renderValue: (user: User) => user.group,
        sortingFunction: (a, b) => stringSortingFunction(a.group, b.group),
      },
      {
        id: 'tags',
        name: 'Tags',
        display: true,
        renderValue: (user: User) => (
          <Tags tagsArray={user.tags.map(tag => tag.name)} />
        ),
        sortingFunction: (a, b) =>
          stringSortingFunction(
            a.tags.map(tag => tag.name).join(', '),
            b.tags.map(tag => tag.name).join(', ')
          ),
      },
    ],
    onSelectAll: (allIds: string[]) => setSelectedUsers(allIds),
    onDeselectAll: () => setSelectedUsers([]),
    filterPredicate,
  })

  return tableProps
}

export default useUserTableSelection
