import type { OptionProps } from '@blueprintjs/core'
import { HTMLSelect } from '@blueprintjs/core'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useMemo, type FC } from 'react'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { FINAL_MILESTONE_FORM } from '../assets/pageContent/finalInformation'
import { getMilestonesWithNames } from '../indexeddb/joins'
import { getVariables } from '../utils'

interface FinalMilestoneFormProps {
  finalMilestone: number
  onFinalMilestoneChange: (finalMilestone: number) => void
}

const FinalMilestoneForm: FC<FinalMilestoneFormProps> = ({
  finalMilestone,
  onFinalMilestoneChange,
}) => {
  const milestones = useLiveQuery(() => getMilestonesWithNames(), [], [])

  const options: OptionProps[] = useMemo(() => {
    if (milestones === undefined || milestones.length === 0) {
      return [
        {
          label: 'No milestones',
          value: 0,
          disabled: true,
        },
      ]
    }

    return [{ label: 'none', value: 0 }, ...getVariables(milestones)]
  }, [milestones])

  return (
    <TooltipLabel label={FINAL_MILESTONE_FORM.finalMilestone}>
      <HTMLSelect
        options={options}
        value={finalMilestone}
        onChange={event =>
          onFinalMilestoneChange(Number(event.currentTarget.value))
        }
      />
    </TooltipLabel>
  )
}

export default memo(FinalMilestoneForm)
