import ExerciseListWrapper from '@/components/ExerciseList/ExerciseListWrapper'
import type { ButtonProps } from '@blueprintjs/core'
import { Button, Overlay2, Section, SectionCard } from '@blueprintjs/core'
import type { Exercise } from '@inject/graphql/fragments/Exercise.generated'
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
}

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

  const [isOpen, setIsOpen] = useState(false)

  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}
      />
      <Overlay2 isOpen={isOpen} onClose={() => setIsOpen(false)}>
        <Section title='Select an exercise'>
          <SectionCard>
            <ExerciseListWrapper
              className={className}
              isSelected={(exercise: Exercise) => exercise.id === exerciseId}
              type='selecting'
              details={(exercise: Exercise) => ({
                onSelect: () => handleSelect(exercise),
              })}
            />
          </SectionCard>
        </Section>
      </Overlay2>
    </>
  )
}

export default ExerciseSelector
