import { forwardRef, ForwardRefRenderFunction, useImperativeHandle, useState } from 'react'
import { FactorySelect } from '../FactorySelect/FactorySelect'
import { useGroups } from '../../contexts/GroupProvider'
import { i18n, I18n } from '../../shared/I18n/I18n'
import { useIntl } from 'react-intl'

interface Handle {
  addGroup(preferredName: string, exported?: string[], mall?: string[]): boolean
}

const PreferencesBase: ForwardRefRenderFunction<Handle> = (_, forwardedRef) => {
  const intl = useIntl()
  const DEFAULT_NAME = i18n(intl, 'page.home.group.add.default_group_name')
  useImperativeHandle(forwardedRef, () => ({
    addGroup(preferredName: string, exported?: string[], mall?: string[]) {
      const name = newGroupValue !== DEFAULT_NAME ? newGroupValue : preferredName
      const result = addGroup(name, exported, mall)
      result && setNewGroupValue(DEFAULT_NAME)
      return result
    }
  }))

  const { addGroup, baseFactories, setBaseFactories, ignoredFactories, setIgnoredFactories } =
    useGroups()
  const [newGroupValue, setNewGroupValue] = useState(DEFAULT_NAME)
  return (
    <>
      <fieldset>
        <legend>
          <I18n id={'page.home.pref.basic.title'} />
        </legend>
        <span>
          <I18n id={'page.home.pref.basic.description'} />
        </span>
        <FactorySelect
          id={'baseFactoriesSelect'}
          factories={baseFactories}
          onSetFactories={setBaseFactories}
          fixInputs={true}
        />
      </fieldset>
      <fieldset>
        <legend>
          <I18n id={'page.home.pref.ignored.title'} />
        </legend>
        <span>
          <I18n id={'page.home.pref.ignored.description'} />
        </span>
        <FactorySelect
          id={'ignoredFactoriesSelect'}
          factories={ignoredFactories}
          onSetFactories={setIgnoredFactories}
        />
      </fieldset>
      <fieldset>
        <legend>
          <I18n id={'page.home.group.add.title'} />
        </legend>
        <input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)} />
        <button
          disabled={!newGroupValue}
          onClick={() => {
            addGroup(newGroupValue)
            setNewGroupValue(DEFAULT_NAME)
          }}
        >
          <I18n id={'page.home.group.add.button_text'} values={{ name: newGroupValue }} />
        </button>
      </fieldset>
    </>
  )
}

export const Preferences = forwardRef(PreferencesBase)
