import {FC, useCallback, useEffect, useMemo, useState} from "react";
import {useLocalStorage} from "../../src/hooks/useLocalStorage";
import {GroupBox} from "./Group/Group";
import {FactorySelect} from "./FactorySelect/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/EntitySpan";
import {useGroups} from "../contexts/GroupProvider";

export const HomeComponent: FC = () => {
  const details = useDetails()
  const {
    groups,
    addGroup,
    doNotSuggest,
    baseFactories,
    setBaseFactories,
    ignoredFactories,
    setIgnoredFactories
  } = useGroups()
  const [newGroupValue, setNewGroupValue] = useState("New group")

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

  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={baseFactories}
          onSetFactories={setBaseFactories}
        />
      </fieldset>
      <fieldset>
        <legend>Ignored Values</legend>
        <FactorySelect
          factories={ignoredFactories}
          onSetFactories={setIgnoredFactories}
        />
      </fieldset>
      <fieldset>
        <legend>Add new groups</legend>
        <input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
        <button disabled={!newGroupValue} onClick={() => {
          addGroup(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={() => {
                addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href])
                setNewGroupValue("New group")
              }}
              onContextMenu={event => {
                event.preventDefault()
                setIgnoredFactories([...ignoredFactories, missing.href])
              }}
              leftClickText={"Create a new factory with this item and name"}
              rightClickText={"Exclude this recipe from suggestions"}
            />
          ))}
        </div>
      </fieldset>
      <div className={styles.grid}>
        {
          groups.map((group, idx) => <GroupBox key={idx} index={idx} />)
        }
      </div>
    </main>
  )
}
