import { Section, SectionCard } from '@blueprintjs/core'
import type { Team } from '@inject/graphql/fragment-types'
import {
  AssignUsersToTeam,
  RemoveUsersFromTeam,
} from '@inject/graphql/mutations'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { useCallback, useState } from 'react'
import { useClient } from 'urql'
import { AUTH_GROUPS } from '../UserTable/utils'
import UserTableSelection from '../UserTableSelection'
import UsersSelection from '../UsersSelection'

interface TeamProps {
  team: Team
}

const TeamComponent: FC<TeamProps> = ({ team }) => {
  const client = useClient()
  const [addOpen, setAddOpen] = useState(false)
  const [selectedUsers, setSelectedUsers] = useState<string[]>([])

  const handleAddToTeam = useCallback(
    (team: Team, userIds: string[]) => {
      client
        .mutation(AssignUsersToTeam, {
          teamId: team.id,
          userIds,
        })
        .toPromise()
        .then(() => {
          notify(
            `User${userIds.length > 0 ? 's' : ''} added to team ${team.name}`
          )
          setAddOpen(false)
        })
        .catch(error => {
          notify(error.message, {
            intent: 'danger',
          })
        })
    },
    [client]
  )

  const handleRemoveFromTeam = useCallback(
    (team: Team, userIds: string[]) => {
      client
        .mutation(RemoveUsersFromTeam, {
          teamId: team.id,
          userIds,
        })
        .toPromise()
        .then(() => {
          notify(
            `User${userIds.length > 1 ? 's' : ''} removed from team ${team.name}`
          )
        })
        .catch(error => {
          notify(error.message, {
            intent: 'danger',
          })
        })
    },
    [client]
  )

  return (
    <>
      <Section
        key={team.id}
        title={`${team.name}${team.role ?? ` - ${team.role}`}`}
      >
        <SectionCard padded>
          <UsersSelection
            users={team.users}
            onRemove={(ids: string[]) => handleRemoveFromTeam(team, ids)}
            onAdd={() => setAddOpen(true)}
          />
        </SectionCard>
      </Section>

      <UserTableSelection
        groups={AUTH_GROUPS}
        open={addOpen}
        setOpen={setAddOpen}
        onAdd={(ids: string[]) => handleAddToTeam(team, ids)}
        selectedUsers={selectedUsers}
        setSelectedUsers={setSelectedUsers}
      />
    </>
  )
}

export default TeamComponent
