import ExerciseList from '@/components/ExerciseList'
import {
  Button,
  Callout,
  Dialog,
  DialogBody,
  DialogFooter,
} from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { Exercise } from '@inject/graphql/fragment-types'
import { useTypedMutation } from '@inject/graphql/graphql'
import { CopyUsersAssignment } from '@inject/graphql/mutations'
import { dialogBody, maximizedDialog } from '@inject/shared/css/dialog'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { useCallback, useState } from 'react'

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

const wrapper = css`
  flex: 1;
  overflow-y: auto;
`

interface CopyAssignmentProps {
  exerciseId: string
  teamCount: number
}

const CopyAssignment: FC<CopyAssignmentProps> = ({ exerciseId, teamCount }) => {
  const [open, setOpen] = useState(false)
  const [selectedExercise, setSelectedExercise] = useState<Exercise>()

  const reset = useCallback(() => {
    setOpen(false)
    setSelectedExercise(undefined)
  }, [])

  const [{ fetching: loading }, copyAssignment] =
    useTypedMutation(CopyUsersAssignment)
  const handleSubmit = useCallback(() => {
    if (!selectedExercise) return

    copyAssignment({
      fromExerciseId: selectedExercise.id,
      toExerciseId: exerciseId,
    })
      .then(() => reset())
      .catch(err => notify(err.message, { intent: 'danger' }))
  }, [copyAssignment, exerciseId, reset, selectedExercise])

  return (
    <>
      <Button
        icon='duplicate'
        text='Copy assignment'
        onClick={() => setOpen(true)}
        active={open}
      />

      <Dialog
        isOpen={open}
        onClose={reset}
        className={maximizedDialog}
        title='Copy assignment from another exercise'
        icon='duplicate'
      >
        <DialogBody className={cx(dialogBody, body)}>
          <Callout icon='info-sign'>
            {`Only exercises with the same team count (${teamCount}) are shown`}
          </Callout>
          <div className={wrapper}>
            <ExerciseList
              filter={exercise =>
                exercise.id !== exerciseId &&
                exercise.teams.length === teamCount
              }
              isSelected={exercise => exercise.id === selectedExercise?.id}
              type='selecting'
              details={exercise => ({
                onSelect: () => setSelectedExercise(exercise),
              })}
            />
          </div>
        </DialogBody>
        <DialogFooter
          actions={
            <Button
              onClick={handleSubmit}
              intent='primary'
              disabled={!selectedExercise}
              title={selectedExercise ? undefined : 'Select an exercise'}
              loading={loading}
            >
              Submit
            </Button>
          }
        />
      </Dialog>
    </>
  )
}

export default CopyAssignment
