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 { useLocation, useNavigate } from 'react-router-dom'
import { useParams } from '../../router'

interface ExerciseSelectorProps {
  buttonProps?: ButtonProps | undefined
  className?: string
  openByDefault?: boolean
}

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

  const [isOpen, setIsOpen] = useState(openByDefault)

  const { exerciseId } = useParams('/analyst/:exerciseId')
  const { pathname } = useLocation()

  // TODO: will have to be reworked if routing changes
  const regex = /\/analyst\/?(\d+)?(\/[^\s]+)?/g
  const match = regex.exec(pathname)
  if (!match)
    throw new Error(
      `ExerciseSelector on page '${pathname}' => doesn't match expected path`
    )
  const suffix = match.at(2) || ''

  const handleSelect = useCallback(
    (exercise: Exercise) => {
      setIsOpen(false)
      nav(`/analyst/${exercise.id}${suffix}`)
    },
    [nav, suffix]
  )

  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 === exerciseId}
            type='selecting'
            details={(exercise: Exercise) => ({
              onSelect: () => handleSelect(exercise),
            })}
          />
        </DialogBody>
      </Dialog>
    </>
  )
}

export default ExerciseSelector
