import type { ButtonProps } from '@blueprintjs/core'
import { Button, Checkbox, NonIdealState } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { RestrictedUser } from '@inject/graphql/fragments/RestrictedUser.generated'
import type { FC } from 'react'
import { useMemo, useState } from 'react'
import Label from './Label'

const wrapper = css`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`

const buttons = css`
  display: flex;
  justify-content: space-between;
`

interface UserSelectionProps {
  users: RestrictedUser[]
  onRemove: (ids: string[]) => void
  onAdd: () => void
}

const UsersSelection: FC<UserSelectionProps> = ({ users, onRemove, onAdd }) => {
  const [selectedUsers, setSelectedUsers] = useState(users.map(() => false))

  const {
    text: removeText,
    title: removeTitle,
    disabled: removeDisabled,
  } = useMemo<ButtonProps>(() => {
    const count = selectedUsers.filter(isSelected => isSelected).length
    return {
      text: `Remove (${count})`,
      title: count === 0 ? 'No users selected' : undefined,
      disabled: count === 0,
    }
  }, [selectedUsers])

  return (
    <div className={wrapper}>
      <div>
        {users.length === 0 && (
          <NonIdealState
            layout='horizontal'
            icon='blocked-person'
            description='There are no users assigned'
          />
        )}
        {users.map((user, i) => (
          <Checkbox
            key={user.id}
            labelElement={<Label user={user} />}
            checked={selectedUsers[i]}
            onChange={() =>
              setSelectedUsers(prev => [
                ...prev.slice(0, i),
                !prev[i],
                ...prev.slice(i + 1),
              ])
            }
          />
        ))}
      </div>
      <div className={buttons}>
        <Button
          onClick={() => {
            onRemove(
              users.filter((_user, i) => selectedUsers[i]).map(user => user.id)
            )
            setSelectedUsers(new Array(users.length).fill(false))
          }}
          icon='cross'
          text={removeText}
          title={removeTitle}
          disabled={removeDisabled}
        />
        <Button intent='primary' onClick={onAdd} icon='plus' text='Add' />
      </div>
    </div>
  )
}

export default UsersSelection
