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

interface FileSelectorProps {
  label: ExtendedLabel
  fileId: number
  onChange: (id: number) => void
}

const FileSelector: FC<FileSelectorProps> = ({ label, fileId, onChange }) => {
  const files = useLiveQuery(() => db.files.toArray(), [], [])

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

    return [
      { label: 'No file', value: 0 },
      ...(files ?? []).map((file: ContentFile) => ({
        value: file.id,
        label: file.name,
      })),
    ]
  }, [files])

  useEffect(() => {
    if (!fileId) {
      onChange(0)
    }
  }, [files, fileId])

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

export default FileSelector
