import type { OptionProps } from '@blueprintjs/core'
import { HTMLSelect } from '@blueprintjs/core'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useEffect, useMemo, type FC } from 'react'
import ToolForm from '../ToolForm'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { db } from '../indexeddb/db'
import type { ToolInfo } from '../indexeddb/types'
import type { ExtendedLabel } from '../types'

interface ToolFormProps {
  label: ExtendedLabel
  toolId: number
  onChange: (id: number) => void
}

const ToolSelector: FC<ToolFormProps> = ({ label, toolId, onChange }) => {
  const tools = useLiveQuery(() => db.tools.toArray(), [], [])

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

    return tools?.map((tool: ToolInfo) => ({
      value: tool.id,
      label: tool.name,
    }))
  }, [tools])

  useEffect(() => {
    if (!toolId && tools && tools.length > 0) {
      onChange(tools[0].id)
    }
  }, [tools, toolId])

  return (
    <div style={{ display: 'flex', width: '100%' }}>
      <TooltipLabel label={label} style={{ flexGrow: '1' }}>
        <HTMLSelect
          options={toolOptions}
          value={toolId}
          onChange={event => onChange(Number(event.currentTarget.value))}
        />
      </TooltipLabel>
      <ToolForm
        buttonProps={{
          minimal: true,
          icon: 'plus',
          style: { marginRight: '1rem' },
        }}
        onAdd={toolId => onChange(toolId)}
      />
    </div>
  )
}

export default memo(ToolSelector)
