import {FC, useCallback, useEffect, useMemo, useState} from "react";
import {useLocalStorage} from "../src/hooks/useLocalStorage";
import {Group} from "./Group";
import {FactorySelect} from "./FactorySelect";
import styles from "./Home.module.css"
import {sortByProperty} from "../src/utils";

interface Group {
  name: string
  factories: string[]
  intermediates: string[]
  inputs: string[]
}

export const HomeComponent: FC = () => {
  const [newGroupValue, setNewGroupValue] = useState("New group")
  const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
  const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])

  const [groups, setGroups] = useLocalStorage<Group[]>('serviceGroups', [])
  const [clientGroups, setClientGroups] = useState<typeof groups>([])

  const doNotSuggest = useMemo<string[]>(() => {
    return groups.flatMap(group => [...group.intermediates, ...group.factories, ...excludedSuggestions])
  }, [groups, excludedSuggestions])

  useEffect(() => setClientGroups(groups), [groups])
  const removeGroup = (idx: number) => setGroups(groups => {
    groups.splice(idx, 1)
    return groups
  })
  const appendGroup = useCallback((name: string) => setGroups(groups => {
    groups.push({name, factories: [], intermediates: [], inputs: []})
    groups.sort(sortByProperty(group => group.name))
    return groups
  }), [setGroups])
  const setFactories = useCallback((idx: number, uids: string[], key: 'intermediates'|'factories'|'inputs') => setGroups(groups => {
    groups[idx][key] = uids
    return groups
  }), [setGroups])
  const renameGroup = useCallback((idx: number, name: string) => setGroups(groups => {
    groups[idx].name = name
    groups.sort(sortByProperty(group => group.name))
    return groups
  }), [setGroups])

  return (
    <main>
      <h1>Factorio Microservices</h1>
      <fieldset>
        <legend>Basic Values</legend>
        <FactorySelect
          factories={basicValues}
          onSetFactories={setBasicValues}
        />
      </fieldset>
      <fieldset>
        <legend>Ignored Values</legend>
        <FactorySelect
          factories={excludedSuggestions}
          onSetFactories={setExcludedSuggestions}
        />
      </fieldset>
      <fieldset>
        <legend>Add new groups</legend>
        <input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
        <button disabled={!newGroupValue} onClick={() => {
          appendGroup(newGroupValue)
          setNewGroupValue("New group")
        }}>
          Add group &quot;{newGroupValue}&quot;
        </button>
      </fieldset>
      <div className={styles.grid}>
        {
          clientGroups.map((group, idx) => <Group
            key={idx}
            outputFactories={group.factories}
            intermediateFactories={group.intermediates}
            inputFactories={group.inputs}
            name={group.name}
            onRemove={() => removeGroup(idx)}
            onRename={(name: string) => renameGroup(idx, name)}
            onSetOutputFactories={uids => setFactories(idx, uids, 'factories')}
            onSetIntermediateFactories={uids => setFactories(idx, uids, 'intermediates')}
            onSetInputFactories={uids => setFactories(idx, uids, 'inputs')}
            doNotSuggest={doNotSuggest}
            onDoIgnore={uid => setExcludedSuggestions([...excludedSuggestions, uid])}
          />)
        }
      </div>
    </main>
  )
}
