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 EmailAddressForm from '../EmailAddressForm'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { db } from '../indexeddb/db'
import type { EmailAddressInfo } from '../indexeddb/types'
import type { ExtendedLabel } from '../types'

interface EmailAddressSelectorProps {
  label: ExtendedLabel
  emailAddressId: number
  onChange: (id: number) => void
}

const EmailAddressSelector: FC<EmailAddressSelectorProps> = ({
  label,
  emailAddressId,
  onChange,
}) => {
  const emailAddresses = useLiveQuery(() => db.emailAddresses.toArray(), [], [])

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

    return emailAddresses?.map((emailAddress: EmailAddressInfo) => ({
      value: emailAddress.id,
      label: emailAddress.address,
    }))
  }, [emailAddresses])

  useEffect(() => {
    if (!emailAddressId && emailAddresses && emailAddresses.length > 0) {
      onChange(Number(emailAddresses[0].id))
    }
  }, [emailAddresses, emailAddressId])

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

export default memo(EmailAddressSelector)
