import { FC, useCallback, useMemo, useState } from 'react'
import { Heading } from '../../shared/Heading'
import { i18n, I18n } from '../../shared/I18n/I18n'
import { Paragraph } from '../../shared/Paragraph/Paragraph'
import styles from './SectionAddMissing.module.css'
import { EntitySpan } from '../EntitySpan/EntitySpan'
import { Section } from '../../shared/Section/Section'
import { EnrichedEntity } from '../../../src/types'
import { useFactories } from '../../contexts/FactoryProvider'
import { useGroups } from '../../contexts/GroupProvider'
import { useIntl } from 'react-intl'
import { Input } from '../../shared/Input/Input'
import { Button } from '../../shared/Button/Button'

export const SectionAddMissing: FC = () => {
  const intl = useIntl()
  const DEFAULT_NAME = useMemo(() => i18n(intl, 'page.home.group.add.default_group_name'), [intl])
  const { factories } = useFactories()
  const { addGroup: addGroupCtx, doNotSuggest, ignoredFactories, setIgnoredFactories } = useGroups()
  const [newGroupValue, setNewGroupValue] = useState(DEFAULT_NAME)
  const addGroup = useCallback(
    (preferredName: string, exported?: string[], mall?: string[]) => {
      const name = newGroupValue !== DEFAULT_NAME ? newGroupValue : preferredName
      const result = addGroupCtx(name, exported, mall)
      result && setNewGroupValue(DEFAULT_NAME)
      return result
    },
    [DEFAULT_NAME, addGroupCtx, newGroupValue]
  )

  const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
    return factories
      .filter(factory => !doNotSuggest.has(factory.href) && factory.recipe)
      .reduce(
        (acc, factory) =>
          (factory.usedBy?.length ?? 0) >= 3
            ? [[...acc[0], factory], acc[1]]
            : [acc[0], [...acc[1], factory]],
        [[], []] as [EnrichedEntity[], EnrichedEntity[]]
      )
  }, [factories, doNotSuggest])

  return (
    <Section color={'secondary'}>
      <Heading type={'section'}>
        <I18n id={'page.home.group.add.title'} />
      </Heading>
      <Input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)} />
      <Button
        className={styles.addBtn}
        disabled={!newGroupValue}
        onClick={() => {
          addGroup(newGroupValue)
          setNewGroupValue(DEFAULT_NAME)
        }}
      >
        <I18n id={'page.home.group.add.button_text'} values={{ name: newGroupValue }} />
      </Button>
      <Heading type={'subsection'}>
        <I18n id={'page.home.group.missing.export.title'} />
      </Heading>
      <Paragraph size={'subtitle'}>
        <I18n id={'page.home.group.missing.export.description'} />
      </Paragraph>
      {missingExport.length ? (
        <div className={styles.entitySpanList}>
          {missingExport.map(missing => (
            <EntitySpan
              key={missing.href}
              value={missing}
              onClick={() => {
                addGroup(missing.name, [missing.href])
              }}
              onContextMenu={event => {
                event.preventDefault()
                setIgnoredFactories([...ignoredFactories, missing.href])
              }}
              leftClickText={i18n(intl, 'page.home.tooltip.action.add_to_new_export')}
              rightClickText={i18n(intl, 'page.home.tooltip.action.exclude_suggestion')}
            />
          ))}
        </div>
      ) : (
        <Paragraph size={'medium'}>
          <em>
            <I18n id={'page.home.group.missing.none'} />
          </em>
        </Paragraph>
      )}
      <Heading type={'subsection'}>
        <I18n id={'page.home.group.missing.mall.title'} />
      </Heading>
      <Paragraph size={'subtitle'}>
        <I18n id={'page.home.group.missing.mall.description'} />
      </Paragraph>
      {missingMall.length ? (
        <div className={styles.entitySpanList}>
          {missingMall.map(missing => (
            <EntitySpan
              key={missing.href}
              value={missing}
              onClick={() => {
                addGroup(missing.name, undefined, [missing.href])
              }}
              onContextMenu={event => {
                event.preventDefault()
                setIgnoredFactories([...ignoredFactories, missing.href])
              }}
              leftClickText={i18n(intl, 'page.home.tooltip.action.add_to_new_mall')}
              rightClickText={i18n(intl, 'page.home.tooltip.action.exclude_suggestion')}
            />
          ))}
        </div>
      ) : (
        <Paragraph size={'medium'}>
          <em>
            <I18n id={'page.home.group.missing.none'} />
          </em>
        </Paragraph>
      )}
    </Section>
  )
}
