import {FC, useCallback, useEffect, useMemo, useState} from "react";
import {useLocalStorage} from "../src/hooks/useLocalStorage";
import {GroupBox} from "./Group";
import {FactorySelect} from "./FactorySelect";
import styles from "./Home.module.css"
import {sortByProperty} from "../src/utils";
import {useDetails} from "../src/hooks/useDetails";
import {Entity, Group} from "../src/types";
import pako from 'pako';
import {EntitySpan} from "./EntitySpan";

export const HomeComponent: FC = () => {
  const details = useDetails()
  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<Group[]>([])

  const doNotSuggest = useMemo<Set<string>>(() => {
    return new Set([...groups.flatMap(group => [...(group.name.includes('Mall') ? group.intermediates : []), ...group.factories]), ...excludedSuggestions, ...basicValues])
  }, [basicValues, groups, excludedSuggestions])

  const basicSet = useMemo<Set<string>>(() => {
    return new Set(basicValues)
  }, [basicValues])

  const exportedSet = useMemo<Set<string>>(() => {
    return new Set(groups
      .filter(group => group.isExported)
      .flatMap(group => group.factories)
    )
  }, [groups])

  const missingFactories = useMemo<Entity[]>(() => {
    return details.filter(detail => !doNotSuggest.has(detail.href) && detail.recipe)
  }, [details, doNotSuggest])

  useEffect(() => setClientGroups(groups), [groups])
  const removeGroup = (idx: number) => setGroups(groups => {
    groups.splice(idx, 1)
    return groups
  })
  const appendGroup = useCallback((name: string, factories: 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])
  const toggleExported = useCallback((idx: number) => setGroups(groups => {
    groups[idx].isExported = !groups[idx].isExported
    groups.sort(sortByProperty(group => group.name))
    return groups
  }), [setGroups])

  const store = () => {
    const string = JSON.stringify(groups)
    const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64')
    const atob = (str: string) => Buffer.from(str, 'base64')
    const compressed = btoa(pako.deflate(string))
    console.log(string.length, compressed.length)
    const uncompressed = pako.inflate(atob(compressed), {to: "string"})
  }

  return (
    <main>
      <h1>Factorio Microservices</h1>
      <button onClick={store}>Store</button>
      <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>
      <fieldset>
        <legend>Missing factories</legend>
        <div className={styles.missingFactories}>
          { missingFactories.map(missing => (
            <EntitySpan
              key={missing.href}
              value={missing}
              onClick={() => {
                appendGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href])
                setNewGroupValue("New group")
              }}
              onContextMenu={event => {
                event.preventDefault()
                setExcludedSuggestions([...excludedSuggestions, missing.href])
              }}
              leftClickText={"Create a new factory with this item and name"}
              rightClickText={"Exclude this recipe from suggestions"}
            />
          ))}
        </div>
      </fieldset>
      <div className={styles.grid}>
        {
          clientGroups.map((group, idx) => <GroupBox
            key={idx}
            group={group}
            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')}
            onToggleExported={() => toggleExported(idx)}
            sets={{doNotSuggest, basic: basicSet, exported: exportedSet}}
            onDoIgnore={uid => setExcludedSuggestions([...excludedSuggestions, uid])}
          />)
        }
      </div>
    </main>
  )
}
