import {FC, useEffect, useState} from "react";
import Select from "react-select";
import {isNonNullable} from "../src/utils";
import details from "../res/details.json";

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

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

export const FactorySelect: FC<Props> = ({factories, onSetFactories}) => {
  const [state, setState] = useState<typeof options>([])
  useEffect(() => {
    setState(factories
      .map(factory => options.find(option => option.value === factory))
      .filter(isNonNullable))
  }, [factories])

  return <Select
    value={state}
    isMulti
    options={options as never}
    onChange={e => {
      setState(e as typeof options)
      onSetFactories(e.map(s => s?.value))
    }}
  />
}
