import ExerciseList from '@/components/ExerciseList'
import type { ButtonProps } from '@blueprintjs/core'
import { Button, Dialog, DialogBody } from '@blueprintjs/core'
import type { Exercise } from '@inject/graphql/fragment-types'
import { dialogBody, maximizedDialog } from '@inject/shared/css/dialog'
import type { FC } from 'react'
import { useCallback, useState } from 'react'
import { useMatch, useNavigate } from 'react-router-dom'

interface ExerciseSelectorProps {
  buttonProps?: ButtonProps | undefined
  className?: string
  openByDefault?: boolean
  to?: 'analyst' | 'instructor' | 'trainee'
}

const ExerciseSelector: FC<ExerciseSelectorProps> = ({
  buttonProps = {},
  className,
  openByDefault = false,
  to = 'analyst',
}) => {
  const nav = useNavigate()

  const [isOpen, setIsOpen] = useState(openByDefault)

  const match = useMatch({
    path: '/:context/:exerciseId/*',
    end: false,
  })

  const handleSelect = useCallback(
    (exercise: Exercise) => {
      setIsOpen(false)
      if (match) {
        nav(`/${to}/${exercise.id}/${match.params['*']}`)
      } else {
        nav(`/${to}/${exercise.id}`)
      }
    },
    [match, nav, to]
  )

  return (
    <>
      <Button
        style={{ whiteSpace: 'nowrap' }}
        onClick={() => setIsOpen(true)}
        {...buttonProps}
      />
      <Dialog
        className={maximizedDialog}
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        title='Select an exercise'
      >
        <DialogBody className={dialogBody}>
          <ExerciseList
            className={className}
            isSelected={(exercise: Exercise) =>
              exercise.id === match?.params?.exerciseId
            }
            type='selecting'
            details={(exercise: Exercise) => ({
              onSelect: () => handleSelect(exercise),
            })}
          />
        </DialogBody>
      </Dialog>
    </>
  )
}

export default ExerciseSelector
