import { FC, memo, useMemo } from 'react'
import Select from 'react-select'
import { isNonNullable } from '../../../src/utils'
import details from '../../../res/details.json'
import styles from './FactorySelect.module.css'
import { EntitySpan } from '../EntitySpan/EntitySpan'

interface Props {
  id: string
  factories: string[]
  onSetFactories: (factories: string[]) => void
}

const options = details.map(detail => ({
  label: detail.name,
  value: detail.href
}))

const FactorySelectBase: FC<Props> = ({ id, factories, onSetFactories }) => {
  const state = useMemo<typeof options>(() => {
    return factories
      .map(factory => options.find(option => option.value === factory))
      .filter(isNonNullable)
  }, [factories])

  return (
    <Select
      id={id}
      instanceId={id}
      value={state}
      components={{
        MultiValueLabel: ({ data, innerProps }) => (
          <EntitySpan {...innerProps} value={data.value} simpleStyle={true} />
        ),
        Option: ({ innerProps, data }) => (
          <div {...innerProps} className={styles.option}>
            <EntitySpan value={data.value} simpleStyle={true} />
          </div>
        )
      }}
      isMulti
      options={options as never}
      onChange={e => {
        onSetFactories(e.map(s => s?.value))
      }}
      className={styles.select}
      classNamePrefix={'factory-select'}
    />
  )
}

export const FactorySelect = memo(FactorySelectBase)
