import Table from '@/components/Table'
import {
  Button,
  ButtonGroup,
  Dialog,
  DialogBody,
  DialogFooter,
} from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { User } from '@inject/graphql/fragment-types'
import { maximizedDialog } from '@inject/shared/css/dialog'
import { useCallback, type Dispatch, type FC, type SetStateAction } from 'react'
import type { AUTH_GROUPS } from '../UserTable/utils'
import useUserTableSelection from './useUserTableSelection'

const body = css`
  display: flex;
  flex-direction: column;
`

interface UserTableSelectionProps {
  open: boolean
  setOpen: Dispatch<SetStateAction<boolean>>
  onAdd: (ids: string[]) => void
  groups: typeof AUTH_GROUPS
  selectedUsers: string[]
  setSelectedUsers: Dispatch<SetStateAction<string[]>>
}

const UserTableSelection: FC<UserTableSelectionProps> = ({
  open,
  groups,
  setOpen,
  onAdd,
  selectedUsers,
  setSelectedUsers,
}) => {
  const handleCancel = useCallback(() => {
    setOpen(false)
    setSelectedUsers([])
  }, [setOpen, setSelectedUsers])

  const tableProps = useUserTableSelection(
    {
      groups,
      selectedUsers,
      setSelectedUsers,
    }
  )

  return (
    <Dialog isOpen={open} onClose={handleCancel} className={maximizedDialog}>
      <DialogBody className={cx(maximizedDialog, body)}>
        <Table<User> {...tableProps} />
      </DialogBody>
      <DialogFooter
        actions={
          <ButtonGroup>
            <Button onClick={handleCancel} 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>
        }
      />
    </Dialog>
  )
}

export default UserTableSelection
