import { Section, SectionCard } from '@blueprintjs/core'
import type { RestrictedUserF } from '@inject/graphql/fragment-types'
import {
  AssignInstructorsToExercise,
  RemoveInstructorsFromExercise,
} from '@inject/graphql/mutations'
import { notify } from '@inject/shared/notification/engine'
import { useCallback, useState, type FC } from 'react'
import { useClient } from 'urql'
import UserTableSelection from '../UserTableSelection'
import UsersSelection from '../UsersSelection'
import { bodySection } from './classes'

interface InstructorsProps {
  users: RestrictedUserF[]
  exerciseId: string
}

const Instructors: FC<InstructorsProps> = ({ users, exerciseId }) => {
  const client = useClient()
  const [addOpen, setAddOpen] = useState(false)
  const [selectedUsers, setSelectedUsers] = useState<string[]>([])

  const handleAddInstructors = useCallback(
    (userIds: string[]) => {
      client
        .mutation(AssignInstructorsToExercise, {
          exerciseId,
          userIds,
        })
        .toPromise()
        .then(() => {
          notify(`Instructor${userIds.length > 1 ? 's' : ''} added`)
          setAddOpen(false)
        })
        .catch(error => {
          notify(error.message, {
            intent: 'danger',
          })
        })
    },
    [client, exerciseId]
  )

  const handleRemoveInstructors = useCallback(
    (userIds: string[]) => {
      client
        .mutation(RemoveInstructorsFromExercise, {
          exerciseId,
          userIds,
        })
        .toPromise()
        .then(() => {
          notify(`Instructor${userIds.length > 1 ? 's' : ''} removed`)
        })
        .catch(error => {
          notify(error.message, {
            intent: 'danger',
          })
        })
    },
    [client, exerciseId]
  )

  return (
    <>
      <Section title='Instructors' icon='intelligence' className={bodySection}>
        <SectionCard padded>
          <Section>
            <SectionCard padded>
              <UsersSelection
                users={users}
                onRemove={ids => handleRemoveInstructors(ids)}
                onAdd={() => setAddOpen(true)}
              />
            </SectionCard>
          </Section>
        </SectionCard>
      </Section>

      <UserTableSelection
        groups={['ADMIN', 'INSTRUCTOR']}
        open={addOpen}
        setOpen={setAddOpen}
        onAdd={(ids: string[]) => handleAddInstructors(ids)}
        selectedUsers={selectedUsers}
        setSelectedUsers={setSelectedUsers}
      />
    </>
  )
}

export default Instructors
